What are dictionaries in Python?
Dictionaries (dicts) in Python are an embedded data structure that represents mutable collections of key-value pairs. Each key in the dictionary is unique and serves to access the corresponding value. Dictionaries are widely used to store related data and provide quick access to items.
Creating dictionaries in Python
Empty dictionary
empty_dict = {}
# or
empty_dict = dict()
Dictionary with elements
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
Creating a dictionary using the dict() function
person = dict(name="Alice", age=30, city="New York")
Creating a dictionary from two lists
keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]
person = dict(zip(keys, values))
print(person) # {'name': 'Alice', 'age': 30, 'city': 'New York'}
Access to dictionary elements
Reading the value by key
print(person["name"]) # Alice
Secure access using the get() method
name = person.get("name")
print(name) # Alice
middle_name = person.get("middle_name", "N/A")
print(middle_name) # N/A
Key availability check
if "name" in person:
print("The key 'name' exists in the dictionary")
Changing and adding elements
Changing the value by key
person["age"] = 31
print(person["age"]) # 31
Adding a new element
person["email"] = "alice@example.com"
print(person)
# {'name': 'Alice', 'age': 31, 'city': 'New York', 'email': 'alice@example.com'}
Updating the dictionary using the update() method
person.update({"email": "alice@example.com", "age": 31})
print(person)
# {'name': 'Alice', 'age': 31, 'city': 'New York', 'email': 'alice@example.com'}
Deleting items from the dictionary
The pop() method
Deletes an element by key and returns its value:
age = person.pop("age")
print(age) # 31
print(person)
# {'name': 'Alice', 'city': 'New York', 'email': 'alice@example.com'}
popitem() method
Deletes and returns the last added key-value pair:
last_item = person.popitem()
print(last_item) # ('email', 'alice@example.com')
print(person)
# {'name': 'Alice', 'city': 'New York'}
The del operator
Deletes an element by key:
del person["city"]
print(person)
# {'name': 'Alice'}
Clear() method
Removes all items from the dictionary:
person.clear()
print(person) # {}
Basic methods of working with dictionaries
The keys() method
Returns a representation of all the keys in the dictionary:
keys = person.keys()
print(keys) # dict_keys(['name', 'age', 'city'])
The values() method
Returns a representation of all values in the dictionary:
values = person.values()
print(values) # dict_values(['Alice', 30, 'New York'])
The items() method
Returns a representation of all key-value pairs:
items = person.items()
print(items) # dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])
Dictionary iteration
Key sorting
for key in person:
print(key)
Iterating through values
for value in person.values():
print(value)
Iterating through key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
Nested dictionaries
Dictionaries can contain other dictionaries as values.:
people = {
"Alice": {"age": 30, "city": "New York"},
"Bob": {"age": 25, "city": "Los Angeles"},
"Charlie": {"age": 35, "city": "Chicago"}
}
print(people["Alice"]["city"]) # New York
Dictionary Generators (Dictionary Comprehensions)
Dictionary generators allow you to create dictionaries using short notation:
squares = {x: x ** 2 for x in range(6)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Dictionary with the condition
even_squares = {x: x ** 2 for x in range(10) if x % 2 == 0}
print(even_squares) # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Combining dictionaries
Using the update() method
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
combined = dict1.copy()
combined.update(dict2)
print(combined) # {'a': 1, 'b': 3, 'c': 4}
Using the ** operator
combined = {**dict1, **dict2}
print(combined) # {'a': 1, 'b': 3, 'c': 4}
Using the | operator (Python 3.9+)
combined = dict1 | dict2
print(combined) # {'a': 1, 'b': 3, 'c': 4}
Practical examples of using dictionaries
Counting the frequency of elements
text = "hello world"
frequency = {}
for char in text:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
print(frequency)
# {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
# Alternative method with get()
frequency = {}
for char in text:
frequency[char] = frequency.get(char, 0) + 1
Grouping elements by keys
data = [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "Los Angeles"},
{"name": "Charlie", "age": 35, "city": "Chicago"},
{"name": "Dave", "age": 30, "city": "New York"}
]
grouped_by_city = {}
for item in data:
city = item["city"]
if city not in grouped_by_city:
grouped_by_city[city] = []
grouped_by_city[city].append(item)
print(grouped_by_city)
Inverting the dictionary
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted) # {1: 'a', 2: 'b', 3: 'c'}
Caching function results
def fibonacci(n, cache={}):
if n in cache:
return cache[n]
if n <= 1:
return n
result = fibonacci(n-1, cache) + fibonacci(n-2, cache)
cache[n] = result
return result
Using collections.defaultdict
To simplify working with data grouping, you can use defaultdict:
from collections import defaultdict
grouped_by_city = defaultdict(list)
for item in data:
grouped_by_city[item["city"]].append(item)
Using collections.Counter
To calculate the frequency of elements, it is convenient to use Counter:
from collections import Counter
text = "hello world"
frequency = Counter(text)
print(frequency) # Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
Best practices for working with dictionaries
- Use the get() method to securely access the keys
- Check for keys using the
in - operator
- Use dictionary generators to create dictionaries based on conditions
- Use defaultdict to simplify data grouping
- Use Counter to count the frequency of elements
Dictionaries are one of the most powerful and versatile data structures in Python, providing efficient key storage and access to data. Their understanding and skillful use greatly simplifies the solution of many programming tasks.
a table with dictionary methods in Python:
method
| The | Description | Usage example | The result |
|---|---|---|---|
dict.get(key, default) |
Gets the value by key, returns default if the key is not found | d.get('name', 'Unknown') |
Value or default |
dict.keys() |
Returns all dictionary keys | d.keys() |
dict_keys(['key1', 'key2']) |
dict.values() |
Returns all dictionary values | d.values() |
dict_values(['val1', 'val2']) |
dict.items() |
Returns key-value pairs | d.items() |
dict_items([('key1', 'val1')]) |
dict.pop(key, default) |
Deletes and returns the key value | d.pop('name', 'Not found') |
Deleted value |
dict.popitem() |
Deletes and returns the last key-value pair | d.popitem() |
('key', 'value') |
dict.clear() |
Clears the dictionary | d.clear() |
{} |
dict.copy() |
Creates a surface copy of the dictionary | d.copy() |
New dictionary |
dict.update(other) |
Updates the dictionary with data from another dictionary | d.update({'new': 'value'}) |
None (modifies the original one) |
dict.setdefault(key, default) |
Gets the value or sets the default | d.setdefault('count', 0) |
Value or default |
dict.fromkeys(keys, value) |
Creates a dictionary with the specified keys | dict.fromkeys(['a', 'b'], 0) |
{'a': 0, 'b': 0} |
Additional operations:
| Operation | Description | Example | The result |
|---|---|---|---|
key in dict |
Checks for the key | 'name' in d |
True/False |
len(dict) |
Number of elements | len(d) |
Number |
del dict[key] |
Deletes an element by key | del d['name'] |
Deletion |
dict[key] = value |
Adds/modifies an element | d['age'] = 25 |
Assignment |
These methods cover the basic operations of working with dictionaries and allow efficient data manipulation.