Python Dictionaries
Introduction to Dictionaries
Dictionaries in Python are versatile data structures that store key-value pairs. They are defined using curly braces {}
and are sometimes called associative arrays, hash tables, or hash maps in other programming languages.
Dictionary Syntax
The basic syntax for a dictionary is:
my_dict = {key1: value1, key2: value2, ...}
- Keys and values are separated by colons
:
. - Key-value pairs (also called items) are separated by commas
,
. - The entire dictionary is enclosed in curly braces
{}
.
Example:
person = {"name": "Alice", "age": 30, "city": "New York"}
Creating Dictionaries
There are several ways to create dictionaries, each with its own syntax:
-
Using curly braces:
empty_dict = {}
person = {"name": "Bob", "age": 25, "job": "Developer"} -
Using the
dict()
constructor:another_person = dict(name="Charlie", age=35, job="Designer")
-
From a list of tuples:
items = [("a", 1), ("b", 2), ("c", 3)]
dict_from_tuples = dict(items) -
Using dict comprehension:
squares = {x: x**2 for x in range(5)}
Accessing and Modifying Dictionaries
Accessing Values
To access a value, use square brackets []
with the key:
person = {"name": "Alice", "age": 30}
print(person["name"]) # Output: Alice
Alternatively, use the get()
method:
age = person.get("age") # Returns 30
unknown = person.get("unknown", "Not found") # Returns "Not found"
Modifying Values
Assign a new value to an existing key:
person["age"] = 31
Adding New Key-Value Pairs
Assign a value to a new key:
person["job"] = "Engineer"
Removing Key-Value Pairs
Use the del
keyword:
del person["age"]
Dictionary Methods in Detail
Let's explore the most important dictionary methods and their syntax:
1. clear()
Syntax: dict.clear()
person.clear()
2. copy()
Syntax: new_dict = dict.copy()
new_person = person.copy()
3. get(key[, default])
Syntax: value = dict.get(key[, default])
age = person.get("age", 0)
4. items()
Syntax: dict.items()
for key, value in person.items():
print(f"{key}: {value}")
5. keys()
Syntax: dict.keys()
keys_list = list(person.keys())
6. values()
Syntax: dict.values()
values_list = list(person.values())
7. pop(key[, default])
Syntax: value = dict.pop(key[, default])
age = person.pop("age", 0)
8. popitem()
Syntax: key, value = dict.popitem()
last_item = person.popitem()
9. setdefault(key[, default])
Syntax: value = dict.setdefault(key[, default])
gender = person.setdefault("gender", "Unknown")
10. update([other])
Syntax: dict.update([other])
person.update({"age": 32, "city": "San Francisco"})
Advanced Dictionary Concepts
Dictionary Comprehensions
Syntax: {key_expression: value_expression for item in iterable}
squares = {x: x**2 for x in range(6)}
Nested Dictionaries
Dictionaries can contain other dictionaries as values:
person = {
"name": "Alice",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
}
}
Accessing nested values:
city = person["address"]["city"]
Common Use Cases for Dictionaries
-
Storing Structured Data:
user_profile = {
"username": "alice_wonder",
"email": "[email protected]",
"preferences": {"theme": "dark", "notifications": True}
} -
Counting Occurrences:
words = ["apple", "banana", "apple", "cherry"]
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1 -
Grouping/Categorizing Data:
students = [
{"name": "Alice", "grade": "A"},
{"name": "Bob", "grade": "B"},
{"name": "Charlie", "grade": "A"}
]
grade_groups = {}
for student in students:
grade_groups.setdefault(student["grade"], []).append(student["name"])
Best Practices and Tips
- Use
dict.get()
ordict.setdefault()
to provide default values for missing keys. - Use the
in
operator to check for key existence:if "name" in person:
print(person["name"]) - Remember that as of Python 3.7, dictionaries maintain insertion order.
- For complex default values, consider using
collections.defaultdict
:from collections import defaultdict
int_dict = defaultdict(int)
int_dict["key"] += 1 # No KeyError, defaults to 0 and then adds 1
Common Pitfalls to Avoid
-
Modifying a Dictionary While Iterating: Instead of:
for key in my_dict:
if some_condition:
del my_dict[key] # Can raise RuntimeErrorUse:
my_dict = {k: v for k, v in my_dict.items() if not some_condition}
-
Using Mutable Objects as Keys:
my_dict = {[1, 2, 3]: "value"} # Raises TypeError
Instead, use immutable types like tuples:
my_dict = {(1, 2, 3): "value"}
-
KeyError When Accessing Non-existent Keys: Instead of:
value = my_dict["non_existent_key"] # Raises KeyError
Use:
value = my_dict.get("non_existent_key", default_value)
Conclusion
Understanding the syntax and operations of dictionaries is crucial for effective Python programming. Dictionaries offer a powerful way to store and retrieve data using meaningful keys. By mastering the syntax and methods associated with dictionaries, you can write more efficient and expressive code. Practice using dictionaries in different scenarios to become proficient in leveraging their full potential in your Python programs.