🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

Dictionaries

AI & DATA SCIENCE // dictionaries

A dictionary is Python's built-in, mutable mapping type that stores key-value pairs and provides fast lookup by key.

Syntax

d = {"a": 1, "b": 2}
d["a"]
d.get("c", 0)

Deep Dive Course

Dictionaries are implemented as hash tables, giving average O(1) time for lookups, insertions, and deletions by key. Keys must be hashable, so ints, strings, and tuples work, but lists and dicts don't, while values can be anything. Since Python 3.7, dictionaries also guarantee that iterating over them yields entries in the order they were inserted.

1Understanding Dictionaries

Dictionaries are implemented as hash tables, giving average O(1) time for lookups, insertions, and deletions by key. Keys must be hashable, so ints, strings, and tuples work, but lists and dicts don't, while values can be anything. Since Python 3.7, dictionaries also guarantee that iterating over them yields entries in the order they were inserted.

💡

Use dict.get(key, default) or dict.setdefault(key, default) instead of checking whether a key exists first — it avoids doing the same hash lookup twice.

editor.html
person = {"name": "Alice", "age": 30}
print(person["name"])
print(person.get("email", "not provided"))
localhost:3000

2Practical Example

Here is a real-world application of Dictionaries showing how it is used in production Python code.

editor.html
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1
print(counts)
localhost:3000

3Best Practices

Follow these guidelines when working with Dictionaries:

1. Use dict.get(key, default) to avoid a KeyError instead of wrapping direct access in try/except

2. Use a dict comprehension instead of a for loop with manual key assignment when building a dictionary from an iterable

3. Use collections.defaultdict when every key should start with a sensible default value, instead of manually checking for existence

⚠️

Tip: Use dict.get(key, default) or dict.setdefault(key, default) instead of checking whether a key exists first — it avoids doing the same hash lookup twice.

editor.html
person = {"name": "Alice", "age": 30}
print(person["name"])
print(person.get("email", "not provided"))
localhost:3000

Examples

Example 01Basic Usage
person = {"name": "Alice", "age": 30}
print(person["name"])
print(person.get("email", "not provided"))
Example 02Advanced Example
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {}
for w in words:
    counts[w] = counts.get(w, 0) + 1
print(counts)

Best Practices

  • Use dict.get(key, default) to avoid a KeyError instead of wrapping direct access in try/except
  • Use a dict comprehension instead of a for loop with manual key assignment when building a dictionary from an iterable
  • Use collections.defaultdict when every key should start with a sensible default value, instead of manually checking for existence

Interview Question

Why must dictionary keys be hashable, and what does that rule out?

Hint: Think about how a hash table looks up a key internally.

A dict finds a key's slot by computing its hash value and using that number to jump almost directly to the right bucket, rather than scanning every entry. That only works correctly if a key's hash never changes after it's inserted, which requires the key to be immutable. This rules out lists and dicts as keys, since they're mutable and therefore explicitly unhashable, while immutable types like strings, numbers, and tuples of hashable items are allowed.

Exercises

MediumPractice using Dictionaries in a real scenario.
View Solution
person = {"name": "Alice", "age": 30}
print(person["name"])
print(person.get("email", "not provided"))

Frequently Asked Questions

Why must dictionary keys be hashable, and what does that rule out?

A dict finds a key's slot by computing its hash value and using that number to jump almost directly to the right bucket, rather than scanning every entry. That only works correctly if a key's hash never changes after it's inserted, which requires the key to be immutable. This rules out lists and dicts as keys, since they're mutable and therefore explicitly unhashable, while immutable types like strings, numbers, and tuples of hashable items are allowed.

Related Functions

dict()setscollections.defaultdict