TL;DR
This guide shows you how to create, add to, access and modify Python dictionaries. Dictionaries store information in key-value pairs – like a real-world dictionary where you look up a word (the key) to find its definition (the value).
Creating a Dictionary
- Empty Dictionary: Start with an empty dictionary using curly braces
{}. - Dictionary with Initial Values: Add key-value pairs directly within the braces, separated by commas. Keys and values are separated by colons.
my_dict = {} # Empty Dictionary
person = {"name": "Alice", "age": 30, "city": "London"} # With initial values
Adding to a Dictionary
- Using Square Brackets: Add new key-value pairs by assigning a value to a new key using square brackets.
- Updating Existing Values: Change the value associated with an existing key in the same way.
my_dict["name"] = "Bob"
my_dict["age"] = 25
person["city"] = "Manchester" # Update city
Accessing Dictionary Values
- Using Square Brackets: Retrieve a value by its key.
get()Method: Use theget()method to retrieve values safely. If the key doesn’t exist, it returnsNone(or a default value you specify). This avoids errors.
name = person["name"] # Accessing name
age = my_dict.get("age") # Accessing age using get()
city = person.get("country", "Unknown") # Get country, default to 'Unknown' if not found
Modifying a Dictionary
- Changing Values: As shown earlier, use square brackets to change the value of an existing key.
- Deleting Key-Value Pairs: Use the
delkeyword followed by the dictionary name and the key in square brackets.
person["age"] = 31 # Change age
del person["city"] # Delete city
Dictionary Methods
keys(): Returns a view object containing all the keys in the dictionary.values(): Returns a view object containing all the values in the dictionary.items(): Returns a view object containing all key-value pairs as tuples.pop(key): Removes and returns the value associated with the specified key. Raises an error if the key is not found.
keys = person.keys()
values = person.values()
items = person.items()
removed_age = person.pop("name") # Remove 'name' and get its value
Iterating Through a Dictionary
- Looping through Keys: Iterate directly over the dictionary to loop through its keys.
- Looping through Values: Use
values()to iterate through the values. - Looping through Key-Value Pairs: Use
items()to iterate through both keys and values simultaneously.
for key in person:
print(key, person[key]) # Loop through keys
for value in person.values():
print(value) # Loop through values
for key, value in person.items():
print(key, value) # Loop through key-value pairs
Checking if a Key Exists
- Using the
inkeyword: Check if a key exists in the dictionary using theinoperator.
if "name" in person:
print("Name exists!")
else:
print("Name does not exist.")

