Lesson

Python Dictionaries

10 min reading
Free Course

Python Dictionaries: Key-Value Lookups and Safe Access

Python dictionaries store data as key: value pairs in curly braces, giving you fast lookups by key name instead of position. Since Python 3.7, a dictionary also remembers the order in which keys were inserted. This lesson covers reading, updating, and merging dictionaries, how to avoid KeyError, and the mistakes that trip up most beginners.

How Python Dictionaries Work

Dictionary keys must be unique and hashable. Strings, numbers, and tuples work as keys. Values can be any Python object, including lists or other dictionaries, so nested data is easy to represent:

user = {"id": 101, "name": "Farhan", "plan": "starter"}
print(user["name"])  # Farhan

"Hashable" roughly means the object cannot change after it is created. That is why Python can find a key quickly, and it is also why a list can't be a key.

Reading, Updating, and Merging Dictionaries

Using user["role"] raises KeyError when "role" is missing. Calling user.get("role", "guest") safely returns a fallback value instead.

user = {"id": 101, "name": "Farhan", "plan": "starter"}
extra = {"plan": "pro", "verified": True}

Safe lookup and Python 3.9+ merge operator

role = user.get("role", "member")
merged = user | extra

for key, value in merged.items():
print(f"{key}: {value}")

Looping with keys(), values(), and items()

  1. .keys() iterates over keys.

  2. .values() iterates over values.

  3. .items() yields (key, value) pairs that you can unpack in a loop, as in the example above.

How to Check It Works

Run the script and compare the output with the list above. If you see KeyError, print user.keys() to see which keys actually exist. If the | line raises a TypeError, run python --version, because your Python is probably older than 3.9.

Dictionary Comprehensions

You can construct or transform dictionaries concisely with a dictionary comprehension instead of filling an empty dict inside a multi-line for loop. When keys might be missing, .setdefault() or collections.defaultdict also avoids repetitive membership checks.

scores = {"alice": 88, "bob": 52, "carol": 94}
passed = {name: score for name, score in scores.items() if score >= 60}
print(passed)  # {'alice': 88, 'carol': 94}

Common Mistakes to Avoid

  • Accessing missing keys with d[key]: Prefer d.get(key) when a key might not exist, or handle KeyError explicitly.

  • Modifying a dictionary while iterating over it: Adding or deleting keys during for k in d: raises RuntimeError; iterate over list(d.keys()) instead.

  • Using mutable lists as keys: Lists are unhashable and raise TypeError; convert composite keys to tuples first.

Conclusion

Python dictionaries are the right tool whenever you need to look something up by name. Use .get() for safe access, | or {**a, **b} for merging, comprehensions for filtering, and Counter for counting. Avoid changing a dictionary's size while looping over it, and use tuples, not lists, for composite keys.

Frequently Asked Questions (FAQs)

What is the difference between .keys(), .values(), and .items()?

.keys() iterates over keys, .values() over values, and .items() yields (key, value) pairs for unpacking in loops.

How do I count items cleanly with a dictionary?

Use collections.Counter(items), or counts[key] = counts. get (key, 0) + 1 to avoid a manual if key in counts check.

Does merged = a | b modify dictionary a?

No. The | operator returns a new dictionary, while a |= b updates a in place.

Are Python dictionaries ordered?

Yes. Since Python 3.7, they keep insertion order. Updating an existing key does not change its position.

How do I check whether a key exists?

Use "role" in user. It checks keys only, not values.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Python Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum