Python Dictionaries Examples
Short, runnable programs that show python dictionaries in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Dictionaries lesson.
1Nested dictionaries
Each user is a dictionary inside the outer dictionary, the same shape as JSON data from an API. Chain keys (and list indexes) to reach the value you need.
users = {
"u1": {"name": "Asha", "langs": ["Python", "SQL"]},
"u2": {"name": "Ben", "langs": ["JavaScript"]},
}
print(users["u1"]["name"])
print(users["u2"]["langs"][0])
users["u2"]["langs"].append("Python")
for user_id, info in users.items():
print(user_id, info["name"], len(info["langs"]))Expected outputAsha
JavaScript
u1 Asha 2
u2 Ben 2
2Building a dictionary from two lists
zip() pairs items up by position and dict() turns those pairs into keys and values.
countries = ["India", "Japan", "Kenya"]
capitals = ["New Delhi", "Tokyo", "Nairobi"]
capital_of = dict(zip(countries, capitals))
print(capital_of)
print(capital_of["Kenya"])Expected output{'India': 'New Delhi', 'Japan': 'Tokyo', 'Kenya': 'Nairobi'}
Nairobi
3Grouping words by their first letter
When the values are lists, create an empty list the first time you see a key, then append to it.
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
by_letter = {}
for word in words:
first = word[0]
if first not in by_letter:
by_letter[first] = []
by_letter[first].append(word)
print(by_letter)Expected output{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
4Merging user settings over defaults
Copy the defaults, then update() with the user's choices: matching keys are overwritten, everything else is kept. The original defaults stay untouched.
defaults = {"theme": "light", "font_size": 14, "autosave": True}
user_prefs = {"theme": "dark"}
settings = defaults.copy()
settings.update(user_prefs)
print(settings)
print("Default theme is still", defaults["theme"])Expected output{'theme': 'dark', 'font_size': 14, 'autosave': True}
Default theme is still light
Practise next
Python Dictionaries exercises → Back to the lesson
Python Dictionary Methods examplesPython Nested Data Structures examplesPython KeyError: What It Means and How to Fix It examplesWorking with JSON in Python examples