Dictionaries in Python
Dictionaries in Python
Section titled “Dictionaries in Python”Introduction
Section titled “Introduction”A dictionary is a mutable, ordered (Python 3.7+) mapping of key-value pairs, backed by a hash table with O(1) average lookup.
Creating Dictionaries
Section titled “Creating Dictionaries”empty = {}person = { "name": "Alice", "age": 30, "email": "alice@example.com"}
# From keyword argumentsconfig = dict(host="localhost", port=5432, database="mydb")
# From list of pairspairs = [("a", 1), ("b", 2), ("c", 3)]d = dict(pairs)
# Dict comprehensionsquares = {x: x**2 for x in range(1, 6)}Accessing Values
Section titled “Accessing Values”person = {"name": "Alice", "age": 30, "city": "NYC"}
print(person["name"]) # Aliceprint(person.get("phone")) # None (safe!)print(person.get("phone", "N/A")) # N/A (default)
print("name" in person) # True — checks keysDictionary Methods
Section titled “Dictionary Methods”d = {"a": 1, "b": 2, "c": 3}
# Adding/Updatingd["d"] = 4 # Add newd["a"] = 99 # Update existingd.update({"b": 20, "e": 5}) # Update multipled.setdefault("f", 100) # Add only if key doesn't exist
# Removingremoved = d.pop("a") # Remove & returnremoved = d.pop("z", None) # Safe removalkey, val = d.popitem() # Remove last inserted
# Merging (Python 3.9+)d1 = {"a": 1, "b": 2}d2 = {"b": 20, "c": 3}merged = d1 | d2 # {'a':1, 'b':20, 'c':3}Iteration
Section titled “Iteration”for key in person: print(key, person[key])
for key, value in person.items(): # Preferred print(f"{key}: {value}")
for value in person.values(): print(value)Specialized Dictionaries
Section titled “Specialized Dictionaries”from collections import defaultdict, Counter
# defaultdict — never raises KeyErrorword_count = defaultdict(int)for word in ["the", "cat", "sat", "the", "mat"]: word_count[word] += 1 # No KeyError!
# Counter — count occurrencescounts = Counter(["apple", "banana", "apple", "cherry"])print(counts.most_common(2)) # [('apple', 2), ('banana', 1)]Nested Dictionaries
Section titled “Nested Dictionaries”users = { "user_1": { "name": "Alice", "address": {"city": "New York", "country": "USA"}, "skills": ["Python", "SQL"] }}
print(users["user_1"]["address"]["city"]) # New YorkWhy It Matters
Section titled “Why It Matters”Dictionaries are fundamental for representing structured data, configuration, counting, caching, and JSON processing.
Interview Questions
Section titled “Interview Questions”Q1: How does Python dict lookup work internally?
A: Python computes hash(key) to find the bucket. If there’s a collision, it probes nearby slots. Average O(1), worst-case O(n).
Q2: How do you merge two dictionaries?
A: {**d1, **d2}, d1 | d2 (Python 3.9+), or d1.update(d2). The second dict’s values win on conflicts.
Practice Exercises
Section titled “Practice Exercises”- Count word frequencies in a text.
- Group items by category using defaultdict(list).
- Invert a dictionary (values become keys).