Chapter 40 of 54

Dictionaries in Python

Think about a phone's contact list. You don't remember that your friend is "contact number 37". You search by name and get the phone number. The name is the key, and the number is the value.

Python's dictionary works the same way. Instead of looking items up by position like a list, you look them up by a meaningful key. Dictionaries are one of the most used data structures in Python, and you'll see them everywhere: in JSON data, configuration settings, counting problems and almost every coding interview.

What is a Dictionary?

A dictionary is a mutable collection of key–value pairs, written as {key: value}. Each key is unique and is used to look up its value.

student = {
    "name": "Asha",
    "age": 21,
    "branch": "CSE"
}

print(student)
print(student["name"])
print(type(student))

Output:

{'name': 'Asha', 'age': 21, 'branch': 'CSE'}
Asha
<class 'dict'>
   key          value
┌──────────┬──────────┐
│ "name"   │ "Asha"   │
│ "age"    │ 21       │
│ "branch" │ "CSE"    │
└──────────┴──────────┘

Key rules to remember:

  • Keys are unique. If you repeat a key, the last value wins.

  • Keys must be hashable (immutable): strings, numbers and tuples work; lists don't. You saw the same rule for set items in the previous chapter.

  • Values can be anything: numbers, strings, lists, even other dictionaries.

  • Order is preserved. Since Python 3.7, a dictionary remembers the order in which keys were inserted.


Creating Dictionaries

empty = {}
prices = {"pen": 10, "book": 250}
config = dict(debug=True, level=3)
pairs = dict([("a", 1), ("b", 2)])
duplicate_keys = {"x": 1, "x": 2}

print(empty)
print(prices)
print(config)
print(pairs)
print(duplicate_keys)

Output:

{}
{'pen': 10, 'book': 250}
{'debug': True, 'level': 3}
{'a': 1, 'b': 2}
{'x': 2}

Tuples can be keys, which is handy for things like grid coordinates. Lists can't:

grid = {(0, 0): "start", (2, 3): "treasure"}
print(grid[(2, 3)])

bad = {[1, 2]: "no"}

Output:

treasure
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')

(Older Python versions show TypeError: unhashable type: 'list'.)


Accessing Values

Square Brackets

d[key] returns the value, but raises a KeyError if the key doesn't exist:

prices = {"pen": 10, "book": 250}

print(prices["pen"])
print(prices["bag"])

Output:

10
KeyError: 'bag'

The get() Method

get() is the safe way. It returns None (or a default you choose) when the key is missing:

prices = {"pen": 10, "book": 250}

print(prices.get("pen"))
print(prices.get("bag"))
print(prices.get("bag", 0))

Output:

10
None
0

Checking if a Key Exists

The in operator checks keys, not values:

prices = {"pen": 10, "book": 250}

print("pen" in prices)
print(10 in prices)
print(10 in prices.values())

Output:

True
False
True

Adding, Updating and Removing

Adding and Updating

The same syntax adds a new key or updates an existing one:

student = {"name": "Ravi", "age": 20}

student["age"] = 21          # key exists, so update
student["city"] = "Pune"     # new key, so add

student.update({"age": 22, "cgpa": 8.4})   # update many at once

print(student)

Output:

{'name': 'Ravi', 'age': 22, 'city': 'Pune', 'cgpa': 8.4}

Updating an existing key keeps its original position; new keys go at the end.

Removing

stock = {"apple": 5, "mango": 0, "kiwi": 12, "grapes": 7}

removed = stock.pop("mango")       # remove a key, get its value
print(removed)

last = stock.popitem()             # remove the LAST inserted pair
print(last)

del stock["apple"]                 # delete by key
print(stock)

print(stock.pop("banana", "not found"))   # default avoids KeyError

stock.clear()
print(stock)

Output:

0
('grapes', 7)
{'kiwi': 12}
not found
{}

popitem() removes pairs in last-in, first-out order and returns them as a tuple. pop() and del raise a KeyError for a missing key unless you give pop() a default.


Looping Through a Dictionary

Dictionaries give you three views: keys(), values() and items().

marks = {"Maths": 92, "Physics": 85, "Chemistry": 78}

for subject in marks:              # same as marks.keys()
    print("Subject:", subject)

total = 0
for score in marks.values():
    total += score
print("Total:", total)

for subject, score in marks.items():   # tuple unpacking
    print(f"{subject} -> {score}")

Output:

Subject: Maths
Subject: Physics
Subject: Chemistry
Total: 255
Maths -> 92
Physics -> 85
Chemistry -> 78

items() gives you (key, value) tuples, and you unpack them right in the for line, just like you did with enumerate() in the Tuples chapter.

Views are live. If the dictionary changes, the view shows the change:

marks = {"Maths": 92}
subjects = marks.keys()

marks["English"] = 88

print(subjects)
print(list(subjects))

Output:

dict_keys(['Maths', 'English'])
['Maths', 'English']

Other Useful Methods

setdefault()

Returns the value for a key; if the key is missing, it first inserts it with a default value:

groups = {}

groups.setdefault("A", []).append("Asha")
groups.setdefault("A", []).append("Arjun")
groups.setdefault("R", []).append("Ravi")

print(groups)

Output:

{'A': ['Asha', 'Arjun'], 'R': ['Ravi']}

fromkeys() and Order-Preserving De-duplication

dict.fromkeys(iterable, value) builds a dictionary with the given keys. Since keys are unique and order is preserved, it removes duplicates while keeping the original order, something a set can't do:

attendance = ["Ravi", "Asha", "Ravi", "Neha", "Asha"]

print(dict.fromkeys(attendance, 0))
print(list(dict.fromkeys(attendance)))

Output:

{'Ravi': 0, 'Asha': 0, 'Neha': 0}
['Ravi', 'Asha', 'Neha']

Merging with |

Since Python 3.9, the | operator merges two dictionaries into a new one, and |= updates in place. When both have the same key, the right side wins:

defaults = {"theme": "light", "font": 14}
user = {"theme": "dark"}

settings = defaults | user

print(settings)

Output:

{'theme': 'dark', 'font': 14}

copy()

Like lists, assigning a dictionary to a new variable doesn't copy it. copy() makes a shallow copy: nested lists or dictionaries inside are still shared.


Nested Dictionaries

Values can themselves be dictionaries, which is how real-world data (like JSON from an API) usually looks:

students = {
    101: {"name": "Asha", "marks": [91, 88]},
    102: {"name": "Ravi", "marks": [76, 84]}
}

print(students[102]["name"])
print(students[101]["marks"][0])

for roll, info in students.items():
    average = sum(info["marks"]) / len(info["marks"])
    print(roll, info["name"], average)

Output:

Ravi
91
101 Asha 89.5
102 Ravi 80.0

Practical Example: Counting Frequencies

Counting how many times each item appears is one of the most common interview patterns. The trick is get(key, 0) + 1:

text = "banana"

freq = {}
for ch in text:
    freq[ch] = freq.get(ch, 0) + 1

print(freq)

most_common = max(freq, key=freq.get)
print("Most common:", most_common)

Output:

{'b': 1, 'a': 3, 'n': 2}
Most common: a

Step by step for "banana":

b → {'b': 1}
a → {'b': 1, 'a': 1}
n → {'b': 1, 'a': 1, 'n': 1}
a → {'b': 1, 'a': 2, 'n': 1}
n → {'b': 1, 'a': 2, 'n': 2}
a → {'b': 1, 'a': 3, 'n': 2}

The same idea solves problems like "two sum", "first non-repeating character" and "check if two strings are anagrams" in O(n) time.


How Fast Are Dictionaries?

A dictionary is a hash table. Python computes the hash of a key and uses it to jump almost directly to where the value is stored.

Operation

Average Time

d[key], d.get(key)

O(1)

d[key] = value

O(1)

del d[key], d.pop(key)

O(1)

key in d

O(1)

value in d.values()

O(n)

Looping, copy()

O(n)

Like sets, these are average times; heavy hash collisions can make single operations O(n), but that's rare in practice.


Common Mistakes

1. Changing the Size While Looping

stock = {"pen": 0, "book": 3}

for item in stock:
    if stock[item] == 0:
        del stock[item]

Output:

RuntimeError: dictionary changed size during iteration

Loop over a copy of the keys instead: for item in list(stock):. (Changing the value of an existing key while looping is fine.)

2. Other Pitfalls

  • Using d[key] on a key that may not exist. Use get() or check with in first.

  • Expecting in to search values. It only checks keys.

  • Using a list as a key. Convert it to a tuple.

  • Expecting duplicate keys to be kept. The later value silently replaces the earlier one.

List vs Dictionary

Feature

List

Dictionary

Access by

Integer index

Key (any hashable value)

Syntax

[10, 20]

{"a": 10, "b": 20}

Search for an item

O(n)

O(1) average (by key)

Best for

Ordered sequence of items

Looking things up by a label

Final Takeaway

A dictionary maps unique keys to values and finds any value by its key in O(1) average time. Use get() for safe access, items() to loop over pairs, and the get(key, 0) + 1 pattern for counting.

Whenever you find yourself searching a list again and again, ask: "Could a dictionary do this lookup in one step?"

Practice: Write a program that takes a sentence and prints each word with the number of times it appears. Then find the first character in a string that doesn't repeat.