Dictionaries in Python
A dictionary is a collection of key-value pairs in Python, where each key is unique and maps to a corresponding value. Dictionaries are mutable, meaning that their contents can be modified after creation. They are unordered, meaning that the order of elements is not guaranteed, and their keys must be of an immutable type (e.g., strings, numbers, tuples).
1. Creating Dictionaries
Dictionaries are created using curly braces {}
, with key-value pairs separated by a colon :
. Each key-value pair is separated by a comma.
Example 1: Creating a Dictionary
# Creating a simple dictionary
person = {"name": "John", "age": 30, "city": "New York"}
# Creating a dictionary with mixed data types as values
student = {"name": "Alice", "age": 22, "grades": [85, 90, 88]}
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
print(student) # Output: {'name': 'Alice', 'age': 22, 'grades': [85, 90, 88]}
- Key: The unique identifier (e.g.,
"name"
,"age"
). - Value: The data associated with the key (e.g.,
"John"
,30
).
2. Accessing Dictionary Elements
You can access the values in a dictionary using the keys.
Example 2: Accessing Dictionary Values
person = {"name": "John", "age": 30, "city": "New York"}
# Accessing a value using a key
print(person["name"]) # Output: John
print(person["age"]) # Output: 30
- If you try to access a key that does not exist, a
KeyError
will be raised. To handle this, you can use the.get()
method.
Example 3: Using .get()
Method
# Using get() to access values (returns None if the key doesn't exist)
print(person.get("name")) # Output: John
print(person.get("address")) # Output: None (no error)
You can also specify a default value to return if the key doesn't exist.
print(person.get("address", "Not available")) # Output: Not available
3. Adding and Modifying Elements
Since dictionaries are mutable, you can add new key-value pairs or modify existing ones.
Example 4: Adding or Modifying Elements
person = {"name": "John", "age": 30}
# Adding a new key-value pair
person["city"] = "New York"
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
# Modifying an existing value
person["age"] = 31
print(person) # Output: {'name': 'John', 'age': 31, 'city': 'New York'}
- If the key exists, the value is updated.
- If the key does not exist, a new key-value pair is added.
4. Removing Elements
You can remove items from a dictionary using several methods, such as del
, .pop()
, or .popitem()
.
Example 5: Removing Elements from a Dictionary
person = {"name": "John", "age": 30, "city": "New York"}
# Using del to remove a key-value pair
del person["age"]
print(person) # Output: {'name': 'John', 'city': 'New York'}
# Using pop() to remove a key-value pair and return the value
city = person.pop("city")
print(city) # Output: New York
print(person) # Output: {'name': 'John'}
# Using popitem() to remove and return an arbitrary key-value pair
item = person.popitem()
print(item) # Output: ('name', 'John')
print(person) # Output: {}
del
removes a key-value pair from the dictionary.pop(key)
removes and returns the value for the specified key.popitem()
removes and returns an arbitrary key-value pair from the dictionary (useful for clearing dictionaries or working with items dynamically).
5. Looping Through Dictionaries
You can loop through a dictionary to access keys, values, or both.
Example 6: Looping Through Keys, Values, and Items
person = {"name": "John", "age": 30, "city": "New York"}
# Looping through keys
for key in person:
print(key)
# Output:
# name
# age
# city
# Looping through values
for value in person.values():
print(value)
# Output:
# John
# 30
# New York
# Looping through key-value pairs
for key, value in person.items():
print(key, value)
# Output:
# name John
# age 30
# city New York
.keys()
returns a view of keys..values()
returns a view of values..items()
returns a view of key-value pairs.
6. Dictionary Comprehension
Just like list comprehensions, Python allows you to create dictionaries using dictionary comprehension, a concise way of building dictionaries dynamically.
Example 7: Dictionary Comprehension
# Creating a dictionary with squares of numbers
squares = {x: x ** 2 for x in range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
You can also add conditional logic in dictionary comprehension:
# Creating a dictionary of even numbers and their squares
even_squares = {x: x ** 2 for x in range(10) if x % 2 == 0}
print(even_squares) # Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
7. Nested Dictionaries
Dictionaries can also contain other dictionaries, creating nested dictionaries. This allows you to represent complex structures like databases or JSON objects.
Example 8: Nested Dictionaries
students = {
"Alice": {"age": 22, "grades": [85, 90, 88]},
"Bob": {"age": 24, "grades": [80, 85, 89]},
}
# Accessing nested dictionary values
print(students["Alice"]["age"]) # Output: 22
print(students["Bob"]["grades"]) # Output: [80, 85, 89]
- Nested dictionaries are accessed by chaining keys, like
students["Alice"]["grades"]
.
8. Merging Dictionaries
You can merge two dictionaries into one using the update()
method or by using the **
unpacking operator.
Example 9: Merging Dictionaries
dict1 = {"name": "John", "age": 30}
dict2 = {"city": "New York", "job": "Engineer"}
# Using update() to merge dictionaries
dict1.update(dict2)
print(dict1) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'job': 'Engineer'}
# Using ** unpacking to merge dictionaries (Python 3.5+)
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'job': 'Engineer'}
update()
updates a dictionary with the key-value pairs from another dictionary.- The
**
unpacking operator can also be used to merge two or more dictionaries into a new one.
9. Summary of Dictionaries
- Key-Value Pairs: A dictionary is a collection of unique keys, each associated with a value.
- Mutable: Dictionaries can be modified after creation (you can add, modify, or remove key-value pairs).
- Accessing Elements: Use keys to access values. You can use
get()
for safer access. - Removing Elements: Use
del
,pop()
, orpopitem()
to remove key-value pairs. - Looping: Loop through keys, values, or both with
.keys()
,.values()
, or.items()
. - Dictionary Comprehension: Create dictionaries in a single line using comprehension.
- Nested Dictionaries: Dictionaries can contain other dictionaries to represent complex data structures.
- Merging: Use
update()
or the**
unpacking operator to merge dictionaries.
Dictionaries are one of the most powerful data structures in Python, providing fast and efficient lookups, making them ideal for tasks like storing configuration data, counting occurrences, or implementing a mapping system.