Home/Learn/Python A–Z/Dictionaries — Hash Maps Done Right

Dictionaries — Hash Maps Done Right

Beginner
Data Structures

Dicts are Python's hash maps: O(1) average lookup, insertion-ordered since 3.7, with get/setdefault patterns that eliminate KeyError boilerplate.

Overview

The dict is Python's most important data structure — the language itself runs on dicts (modules, classes, and keyword arguments are all dicts underneath). Keys must be hashable (str, int, tuple), lookups average O(1), and since Python 3.7 dicts preserve insertion order. Master the access patterns — get() with defaults, setdefault(), and dict comprehensions — because frequency-counting and grouping are the openers of countless interview problems.

Access Patterns That Avoid KeyError

d[key] raises KeyError if missing; d.get(key, default) returns a fallback; setdefault inserts-and-returns a default. The counting and grouping idioms below appear in interviews weekly.

get / setdefault — counting and grouping
marks = {"dsa": 85, "java": 90}

print(marks["dsa"])              # 85
# print(marks["sql"])            # KeyError!
print(marks.get("sql"))          # None — safe
print(marks.get("sql", 0))       # 0 — with default

# Frequency count — THE interview idiom
freq = {}
for ch in "engineering":
    freq[ch] = freq.get(ch, 0) + 1
print(freq)   # {'e': 2, 'n': 3, 'g': 2, 'i': 2, 'r': 1}

# Grouping with setdefault
by_dept = {}
for name, dept in [("Asha", "CS"), ("Ravi", "IT"), ("Neha", "CS")]:
    by_dept.setdefault(dept, []).append(name)
print(by_dept)   # {'CS': ['Asha', 'Neha'], 'IT': ['Ravi']}

del marks["java"]                 # remove
score = marks.pop("dsa", 0)       # remove & return (with default)

Iteration, Merging & Ordering

Iterate .items() for pairs. Merge with {**a, **b} or the | operator (3.9+); right side wins conflicts. Insertion order is guaranteed (3.7+) — but for sorting by value you still sort explicitly.

items(), value-sorting, | merge, comprehensions
scores = {"asha": 91, "ravi": 78, "neha": 96}

for name, score in scores.items():
    print(name, score)

# Sort a dict by VALUE, descending — very common ask
top = dict(sorted(scores.items(), key=lambda kv: -kv[1]))
print(top)          # {'neha': 96, 'asha': 91, 'ravi': 78}

# Merging (3.9+)
defaults = {"theme": "dark", "lang": "en"}
user     = {"lang": "hi"}
final = defaults | user            # {'theme': 'dark', 'lang': 'hi'}

# Dict comprehension
squares = {n: n * n for n in range(1, 6)}

# Keys must be hashable
ok  = {(1, 2): "cell"}             # tuple key fine
# bad = {[1, 2]: "x"}              # TypeError: unhashable type: 'list'

Key Points to Remember

  • 1Average O(1) get/set/delete/contains; keys must be hashable
  • 2Insertion order preserved since Python 3.7 (guaranteed, not an accident)
  • 3freq[k] = freq.get(k, 0) + 1 and setdefault(k, []).append(v) — memorize both idioms
  • 4Merge: {**a, **b} or a | b — right-most wins duplicate keys

Interview Questions

Sign in to ask Aria
1

How would you count character frequency in a string? What is the complexity?

EasyZoho
2

Are Python dicts ordered? Since which version, and is it guaranteed?

MediumPaytm
3

Sort a dictionary by its values in descending order.

MediumSwiggy

Ask Aria about Dictionaries — Hash Maps Done Right

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…