Python Dictionaries

What is a Python Dictionary?

A dictionary in Python is an unordered, mutable and indexed collection that stores data as key-value pairs.

Key Features of Python Dictionaries:

  1. Key-Value Pairs: Each element in a dictionary consists of a key and its associated value.
  2. Unordered: The order of elements in a dictionary is not guaranteed (in Python 3.7+, dictionaries maintain insertion order).
  3. Mutable: You can add, update, or remove elements in a dictionary.
  4. Unique Keys: Keys must be unique and immutable (strings, numbers or tuples). Values can be of any type.

How to Create a Dictionary in Python?

You can create a dictionary using curly braces { } or the built-in dict() function.

Syntax:

dictionary_name = {key1: value1, key2: value2, ...}

Examples:

# Creating a dictionary with curly braces
student = {"name": "John", "age": 21, "grade": "A"}

# Using the dict() function
employee = dict(id=101, name="Alice", salary=50000)
print(employee) # Output: {'id': 101, 'name': 'Alice', 'salary': 50000}

Accessing Dictionary Elements

You can access dictionary elements by referring to their keys.

Examples:

# Accessing dictionary values
student = {"name": "John", "age": 21, "grade": "A"}
print(student["name"]) # Output: John

# Using the get() method
print(student.get("age")) # Output: 21

# Key not found
print(student.get("address", "Not Available")) # Output: Not Available

Adding and Updating Dictionary Items

You can add new key-value pairs or update existing ones by assigning values to keys.

Examples:

# Adding a new key-value pair
student = {"name": "John", "age": 21}
student["grade"] = "A"
print(student) # Output: {'name': 'John', 'age': 21, 'grade': 'A'}

# Updating an existing value
student["age"] = 22
print(student) # Output: {'name': 'John', 'age': 22, 'grade': 'A'}

Removing Items from a Dictionary

Python dictionaries provide multiple methods to remove elements.

MethodDescription
pop(key)Removes the item with the specified key and returns its value.
popitem()Removes and returns the last key-value pair (insertion order maintained).
delDeletes an item or the entire dictionary.
clear()Removes all elements from the dictionary.

Examples:

# Removing an item using pop()
student = {"name": "John", "age": 21, "grade": "A"}
grade = student.pop("grade")
print(grade) # Output: A
print(student) # Output: {'name': 'John', 'age': 21}

# Using del
del student["age"]
print(student) # Output: {'name': 'John'}

# Clearing the dictionary
student.clear()
print(student) # Output: {}

Dictionary Methods

Python provides several built-in methods for working with dictionaries.

MethodDescription
keys()Returns a view object of all keys.
values()Returns a view object of all values.
items()Returns a view object of all key-value pairs.
update(other)Updates the dictionary with elements from another dictionary or iterable.
copy()Creates a shallow copy of the dictionary.

Examples:

# Using dictionary methods
student = {"name": "John", "age": 21, "grade": "A"}

print(student.keys()) # Output: dict_keys(['name', 'age', 'grade'])
print(student.values()) # Output: dict_values(['John', 21, 'A'])
print(student.items()) # Output: dict_items([('name', 'John'), ('age', 21), ('grade', 'A')])

# Updating a dictionary
student.update({"age": 22, "address": "123 Street"})
print(student) # Output: {'name': 'John', 'age': 22, 'grade': 'A', 'address': '123 Street'}

Nested Dictionaries

Dictionaries can store other dictionaries as values, creating nested structures.

Examples:

# Nested dictionary example
students = {
"student1": {"name": "John", "age": 21},
"student2": {"name": "Alice", "age": 22}
}

# Accessing nested dictionary values
print(students["student1"]["name"]) # Output: John

Iterating Through a Dictionary

You can iterate through keys, values or key-value pairs in a dictionary.

Examples:

# Iterating through keys
student = {"name": "John", "age": 21, "grade": "A"}
for key in student:
print(key, student[key])

# Iterating through items
for key, value in student.items():
print(f"{key}: {value}")

Use Cases of Python Dictionaries

Storing Configuration Data:

config = {"host": "localhost", "port": 8080}

Counting Occurrences:

from collections import Counter
data = ["apple", "banana", "apple", "cherry"]
count = dict(Counter(data))
print(count) # Output: {'apple': 2, 'banana': 1, 'cherry': 1}

Mapping Keys to Functions:

def add(a, b): return a + b
def subtract(a, b): return a - b

operations = {"add": add, "subtract": subtract}
print(operations["add"](5, 3)) # Output: 8

Leave a Comment