Python is a powerful and versatile programming language known for its simplicity and readability. One of its most essential and flexible data structures is the dictionary. Dictionaries are crucial for storing and managing data using key-value pairs, making them indispensable in various programming scenarios. This comprehensive guide will delve deep into Python dictionaries, covering everything from basic operations to advanced techniques, complete with examples and explanations to enhance your understanding.
A dictionary in Python is an unordered, mutable collection of data values used to store data values like a map. Unlike sequences (which are indexed by a range of numbers), dictionaries are indexed by keys, which can be of any immutable type (e.g., strings, numbers, tuples).
Features of Python Dictionaries:
person = {
"name": "Alice",
"age": 30,
"profession": "Engineer"
}
You can create an empty dictionary in two ways:
# Method 1
empty_dict = {}
# Method 2
empty_dict = dict()
Create a dictionary with initial key-value pairs:
student = {
"name": "John Doe",
"age": 20,
"courses": ["Math", "Science"]
}
dict()
ConstructorYou can create dictionaries using the dict()
constructor with keyword arguments or a list of tuples:
Using Keyword Arguments:
car = dict(make="Toyota", model="Corolla", year=2020)
print(car)
# Output: {'make': 'Toyota', 'model': 'Corolla', 'year': 2020}
Using a List of Tuples:
items = [("apple", 3), ("banana", 2), ("cherry", 5)]
fruit_counts = dict(items)
print(fruit_counts)
# Output: {'apple': 3, 'banana': 2, 'cherry': 5}
Access the value associated with a key using square brackets []
:
person = {
"name": "Alice",
"age": 30,
"profession": "Engineer"
}
print(person["name"]) # Output: Alice
print(person["profession"]) # Output: Engineer
[]
raises a KeyError
.# This will raise a KeyError
# print(person["salary"])
get()
MethodThe get()
method returns the value for a specified key if the key is in the dictionary. If not, it returns None or a default value if provided.
print(person.get("age")) # Output: 30
print(person.get("salary")) # Output: None
print(person.get("salary", 0)) # Output: 0
Add a new key-value pair by assigning a value to a new key:
person["salary"] = 70000
print(person)
# Output: {'name': 'Alice', 'age': 30, 'profession': 'Engineer', 'salary': 70000}
Update the value of an existing key:
person["age"] = 31
print(person["age"]) # Output: 31
Using del
Keyword:
del person["profession"]
print(person)
# Output: {'name': 'Alice', 'age': 31, 'salary': 70000}
Using pop()
Method:
salary = person.pop("salary")
print(salary) # Output: 70000
print(person)
# Output: {'name': 'Alice', 'age': 31}
Using popitem()
Method:
Removes and returns the last inserted key-value pair (since Python 3.7).
person["city"] = "New York"
last_item = person.popitem()
print(last_item) # Output: ('city', 'New York')
print(person)
# Output: {'name': 'Alice', 'age': 31}
Using clear()
Method:
Removes all items from the dictionary.
person.clear()
print(person) # Output: {}
keys()
Returns a view object containing the dictionary's keys.
keys = person.keys()
print(keys) # Output: dict_keys(['name', 'age'])
values()
Returns a view object containing the dictionary's values.
values = person.values()
print(values) # Output: dict_values(['Alice', 31])
items()
Returns a view object containing the dictionary's key-value pairs as tuples.
items = person.items()
print(items) # Output: dict_items([('name', 'Alice'), ('age', 31)])
update()
Updates the dictionary with key-value pairs from another dictionary or iterable.
new_info = {"profession": "Engineer", "city": "New York"}
person.update(new_info)
print(person)
# Output: {'name': 'Alice', 'age': 31, 'profession': 'Engineer', 'city': 'New York'}
pop()
Removes the specified key and returns its value.
age = person.pop("age")
print(age) # Output: 31
print(person) # Output: {'name': 'Alice', 'profession': 'Engineer', 'city': 'New York'}
popitem()
Removes and returns the last inserted key-value pair.
last_item = person.popitem()
print(last_item) # Output: ('city', 'New York')
print(person) # Output: {'name': 'Alice', 'profession': 'Engineer'}
clear()
Removes all items from the dictionary.
person.clear()
print(person) # Output: {}
Dictionary comprehensions provide a concise way to create dictionaries.
new_dict = {key_expression: value_expression for item in iterable}
Create a dictionary mapping numbers to their squares:
squares = {x: x**2 for x in range(1, 6)}
print(squares)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Include an if
clause to filter items.
even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares)
# Output: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
A dictionary can contain other dictionaries, creating nested structures.
employees = {
"emp1": {
"name": "John",
"age": 28,
"department": "Sales"
},
"emp2": {
"name": "Emma",
"age": 32,
"department": "Marketing"
}
}
Use multiple keys to access nested values.
print(employees["emp1"]["name"]) # Output: John
print(employees["emp2"]["department"]) # Output: Marketing
You can loop through dictionaries to access keys, values, or both.
Iterate Over Keys:
for key in person:
print(key)
# Output:
# name
# profession
Iterate Over Values:
for value in person.values():
print(value)
# Output:
# Alice
# Engineer
Iterate Over Key-Value Pairs:
for key, value in person.items():
print(f"{key}: {value}")
# Output:
# name: Alice
# profession: Engineer
Similarities:
Differences:
# List
colors = ["red", "green", "blue"]
print(colors[0]) # Output: red
# Dictionary
color_codes = {"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"}
print(color_codes["red"]) # Output: #FF0000
Keys must be of an immutable data type:
# Valid key
my_dict = {(1, 2): "point"}
print(my_dict)
# Invalid key
# my_dict = {[1, 2]: "point"} # TypeError: unhashable type: 'list'
Problem:
Count the number of occurrences of each word in a text.
text = "To be or not to be that is the question"
words = text.lower().split()
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
print(word_counts)
{'to': 2, 'be': 2, 'or': 1, 'not': 1, 'that': 1, 'is': 1, 'the': 1, 'question': 1}
Explanation:
get()
method to handle missing keys.Problem:
Invert a dictionary, swapping keys and values.
original_dict = {'a': 1, 'b': 2, 'c': 3}
inverted_dict = {value: key for key, value in original_dict.items()}
print(inverted_dict)
{1: 'a', 2: 'b', 3: 'c'}
keys()
, values()
, items()
, update()
, pop()
, and clear()
.Python dictionaries are a fundamental data structure that allows for efficient storage and retrieval of data using key-value pairs. They are essential for a wide range of programming tasks, from simple data mapping to complex data handling.
By mastering dictionaries, you can:
Remember to practice creating, modifying, and working with dictionaries to solidify your understanding and become proficient in Python programming.