How to Use Dictionary in Python: A Complete Guide for Beginners
Python dictionaries are one of the most versatile and powerful data structures in the language, allowing you to store and manipulate key-value pairs efficiently. Unlike lists that use numerical indices, dictionaries use keys to access values, making data retrieval faster and more intuitive. Whether you're building a simple contact book, managing configuration settings, or working with JSON data, understanding how to use dictionaries in Python is essential for any programmer Less friction, more output..
Some disagree here. Fair enough.
What is a Python Dictionary?
A dictionary in Python is an unordered, mutable collection of key-value pairs enclosed in curly braces {}. And each key must be unique and immutable (like strings, numbers, or tuples), while values can be of any data type including lists, other dictionaries, or functions. Dictionaries are also known as hash maps or associative arrays in other programming languages.
Here's a basic example:
student_grades = {
"Alice": 85,
"Bob": 92,
"Charlie": 78
}
Creating Dictionaries in Python
There are several ways to create dictionaries in Python, each suited for different scenarios:
Method 1: Using Curly Braces
The most common way is using curly braces with key-value pairs separated by colons:
person = {
"name": "Sarah",
"age": 25,
"city": "New York"
}
Method 2: Using the dict() Constructor
You can also create dictionaries using the built-in dict() function:
car = dict(brand="Tesla", model="Model 3", year=2023)
Method 3: Empty Dictionary
To create an empty dictionary that you'll populate later:
inventory = {}
Accessing Dictionary Elements
Accessing values in a dictionary is straightforward using square brackets with the key name:
print(person["name"]) # Output: Sarah
On the flip side, if the key doesn't exist, this method will raise a KeyError. Here's the thing — to safely access potentially missing keys, use the get() method:
print(person. get("age")) # Output: 25
print(person.get("country")) # Output: None (no error)
print(person.
## Adding and Updating Dictionary Items
Dictionaries are mutable, meaning you can add new key-value pairs or update existing ones after creation:
### Adding New Items
```python
person["email"] = "sarah@example.com"
print(person)
# Output: {'name': 'Sarah', 'age': 25, 'city': 'New York', 'email': 'sarah@example.com'}
Updating Existing Values
person["age"] = 26
print(person["age"]) # Output: 26
Using update() Method
The update() method merges another dictionary into the current one:
additional_info = {"phone": "555-1234", "age": 27}
person.update(additional_info)
print(person)
# Output: {'name': 'Sarah', 'age': 27, 'city': 'New York', 'email': 'sarah@example.com', 'phone': '555-1234'}
Removing Items from Dictionaries
Python provides multiple methods to remove items from dictionaries:
Using del Statement
Removes a specific key-value pair or the entire dictionary:
del person["city"] # Removes the "city" key
print(person)
# Output: {'name': 'Sarah', 'age': 26, 'email': 'sarah@example.com', 'phone': '555-1234'}
Using pop() Method
Removes and returns the value of a specified key:
removed_age = person.pop("age")
print(removed_age) # Output: 26
print(person)
# Output: {'name': 'Sarah', 'email': 'sarah@example.com', 'phone': '555-1234'}
Using popitem() Method
Removes and returns the last inserted key-value pair (Python 3.7+):
last_item = person.popitem()
print(last_item) # Output: ('phone', '555-1234')
Using clear() Method
Empties the entire dictionary:
person.clear()
print(person) # Output: {}
Dictionary Methods and Built-in Functions
Python dictionaries come with numerous useful methods that make data manipulation easier:
keys(), values(), and items()
These methods return view objects that display dictionary keys, values, or key-value pairs respectively:
student_scores = {"math": 90, "science": 85, "english": 95}
print(student_scores.keys()) # Output: dict_keys(['math', 'science', 'english'])
print(student_scores.values()) # Output: dict_values([90, 85, 95])
print(student_scores.
### len() Function
Returns the number of key-value pairs in a dictionary:
```python
print(len(student_scores)) # Output: 3
copy() Method
Creates a shallow copy of the dictionary:
scores_copy = student_scores.copy()
scores_copy["math"] = 95
print(student_scores["math"]) # Output: 90 (original unchanged)
Iterating Through Dictionaries
Looping through dictionaries is a common operation when processing data:
Iterating Through Keys
for subject in student_scores:
print(f"{subject}: {student_scores[subject]}")
Iterating Through Items
for subject, score in student_scores.items():
print(f"{subject}: {score}")
Iterating Through Values
for score in student_scores.values():
print(score)
Nested Dictionaries
Dictionaries can contain other dictionaries, creating complex data structures useful for organizing hierarchical data:
school = {
"class_10A": {
"teacher": "Mr. Johnson",
"students": 25,
"subjects": ["Math", "Science", "English"]
},
"class_10B": {
"teacher": "Ms. Smith",
"students": 22,
"subjects": ["History", "Geography", "Biology"]
}
}
# Accessing nested data
print(school["class_10A"]["teacher"]) # Output: Mr. Johnson
print(school["class_10B"]["subjects"][1]) # Output: Geography
Dictionary Comprehension
Similar to list comprehension, Python supports dictionary comprehension for creating dictionaries concisely:
# Creating squares of numbers 1-5
squares = {x: x**2 for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# With condition
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}
Common Use Cases and Best Practices
When to Use Dictionaries
Dictionaries are ideal when you need:
- Fast lookups based on unique keys
- Organized storage of related information
- Flexible data structures that can grow dynamically
- Representation of real-world objects with attributes
Best Practices
- Use meaningful key names: Choose descriptive keys that clearly indicate what the value represents
- Handle missing keys gracefully: Use
get() method instead of direct indexing when a key might not exist:
print(student_scores.get("history")) # Output: None
print(student_scores.get("history", 0)) # Output: 0
Direct access with student_scores["history"] raises a KeyError if the key does not exist, while get() safely returns None or a default value Most people skip this — try not to..
print(student_scores["history"]) # Raises KeyError
Membership Testing
You can check whether a key exists in a dictionary using in:
print("math" in student_scores) # Output: True
print("history" in student_scores) # Output: False
It's useful when you need to perform an action only if a certain key is present.
More Useful Dictionary Methods
update() Method
The update() method adds or changes multiple key-value pairs at once:
student_scores.update({"history": 88, "geography": 91})
print(student_scores)
# Output: {'math': 90, 'science': 85, 'english': 95, 'history': 88, 'geography': 91}
It can also be used to modify existing values:
student_scores.update({"math": 92})
print(student_scores["math"]) # Output: 92
setdefault() Method
The setdefault() method adds a key with a default value only if the key does not already exist:
student_scores.setdefault("history", 0)
print(student_scores)
# Output: {'math': 90, 'science': 85, 'english': 95, 'history':