Dictionaries
Prerequisites: Variables, data types, operators, loops, strings, lists
1. What is a Dictionary?
A dictionary is an unordered collection of key-value pairs. Each key maps to a value, like a real dictionary where a word (key) maps to its definition (value).
# key : value pairs
student = {"name": "Rahul", "age": 17, "class": 12}
Key properties:
- Keys must be immutable (strings, numbers, tuples) and unique
- Values can be of any type and can be duplicated
- Dictionaries are mutable, you can add, change, and remove pairs, As of Python 3.7+, dictionaries maintain insertion order
2. Creating Dictionaries
2.1 Using Curly Braces {}
empty = {}
student = {"name": "Rahul", "age": 17, "marks": 85}
print(student)
print(type(student))
Output:
{'name': 'Rahul', 'age': 17, 'marks': 85}
<class 'dict'>
2.2 Using dict Function
# Using keyword arguments
d1 = dict(name="Rahul", age=17, marks=85)
print(d1)
# Using list of tuples
d2 = dict([("name", "Rahul"), ("age", 17)])
print(d2)
# Using zip with two lists
keys = ["a", "b", "c"]
values = [1, 2, 3]
d3 = dict(zip(keys, values))
print(d3)
Output:
{'name': 'Rahul', 'age': 17, 'marks': 85}
{'name': 'Rahul', 'age': 17}
{'a': 1, 'b': 2, 'c': 3}
2.3 Using Dictionary Comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
3. Accessing Values
3.1 Using Square Brackets d[key]
student = {"name": "Rahul", "age": 17, "marks": 85}
print(student["name"])
print(student["marks"])
# print(student["grade"]) # KeyError: 'grade'
Output:
Rahul
85
3.2 Using get Method
student = {"name": "Rahul", "age": 17, "marks": 85}
print(student.get("name"))
print(student.get("grade")) # None (no error)
print(student.get("grade", "N/A")) # "N/A" (default value)
Output:
Rahul
None
N/A
Key difference: d[key] raises KeyError if key does not exist; d.get(key) returns None (or a default value).
4. Adding and Modifying Entries
student = {"name": "Rahul", "age": 17}
# Add a new key-value pair
student["marks"] = 85
print(student)
# Modify an existing value
student["age"] = 18
print(student)
Output:
{'name': 'Rahul', 'age': 17, 'marks': 85}
{'name': 'Rahul', 'age': 18, 'marks': 85}
Note: If the key already exists, the value is updated. If the key does not exist, a new pair is added.
5. Dictionaries are MUTABLE, Keys are IMMUTABLE
# Dictionary itself is mutable
d = {"a": 1, "b": 2}
d["c"] = 3 # add
d["a"] = 99 # modify
del d["b"] # delete
print(d)
# Keys must be immutable types
valid = {
"name": "Rahul", # string key -- OK
42: "answer", # integer key -- OK
(1, 2): "tuple key", # tuple key -- OK
}
# invalid = {[1, 2]: "list key"} # TypeError: unhashable type: 'list'
Output:
{'a': 99, 'c': 3}
Keys must be unique:
d = {"a": 1, "b": 2, "a": 3} # duplicate key "a"
print(d) # last value wins
Output:
{'a': 3, 'b': 2}
6. Traversing a Dictionary
6.1 Iterating Over Keys (default)
d = {"name": "Rahul", "age": 17, "marks": 85}
for key in d:
print(key, ":", d[key])
Output:
name : Rahul
age : 17
marks : 85
6.2 Using keys, values, items
d = {"name": "Rahul", "age": 17, "marks": 85}
# Keys only
for key in d.keys:
print(key, end=" ")
print
# Values only
for val in d.values:
print(val, end=" ")
print
# Key-value pairs
for key, val in d.items:
print(f"{key} = {val}")
Output:
name age marks
Rahul 17 85
name = Rahul
age = 17
marks = 85
7. Dictionary Methods
7.1 len, Number of key-value pairs
d = {"a": 1, "b": 2, "c": 3}
print(len(d))
Output:
3
7.2 dict, Create a dictionary
d = dict(name="Rahul", age=17)
print(d)
Output:
{'name': 'Rahul', 'age': 17}
7.3 keys, Return all keys
Syntax: dict.keys
d = {"name": "Rahul", "age": 17, "marks": 85}
print(d.keys)
print(list(d.keys)) # convert to list
Output:
dict_keys(['name', 'age', 'marks'])
['name', 'age', 'marks']
7.4 values, Return all values
Syntax: dict.values
d = {"name": "Rahul", "age": 17, "marks": 85}
print(d.values)
print(list(d.values))
Output:
dict_values(['Rahul', 17, 85])
['Rahul', 17, 85]
7.5 items, Return all key-value pairs as tuples
Syntax: dict.items
d = {"name": "Rahul", "age": 17, "marks": 85}
print(d.items)
print(list(d.items))
Output:
dict_items([('name', 'Rahul'), ('age', 17), ('marks', 85)])
[('name', 'Rahul'), ('age', 17), ('marks', 85)]
7.6 get, Get value for key with optional default
Syntax: dict.get(key[, default])
d = {"name": "Rahul", "age": 17}
print(d.get("name")) # Rahul
print(d.get("marks")) # None
print(d.get("marks", 0)) # 0 (default)
Output:
Rahul
None
0
7.7 update, Update dictionary with another dictionary
Syntax: dict.update(other_dict)
d = {"name": "Rahul", "age": 17}
d.update({"age": 18, "marks": 85})
print(d)
Output:
{'name': 'Rahul', 'age': 18, 'marks': 85}
7.8 del, Delete a key-value pair
Syntax: del dict[key]
d = {"name": "Rahul", "age": 17, "marks": 85}
del d["age"]
print(d)
# del d["grade"] # KeyError
Output:
{'name': 'Rahul', 'marks': 85}
7.9 clear, Remove all items
Syntax: dict.clear
d = {"a": 1, "b": 2, "c": 3}
d.clear
print(d)
Output:
{}
7.10 fromkeys, Create dictionary with keys and a default value
Syntax: dict.fromkeys(sequence[, value])
keys = ["name", "age", "marks"]
d = dict.fromkeys(keys)
print(d)
d2 = dict.fromkeys(keys, 0)
print(d2)
Output:
{'name': None, 'age': None, 'marks': None}
{'name': 0, 'age': 0, 'marks': 0}
7.11 copy, Create a shallow copy
Syntax: dict.copy
d1 = {"a": 1, "b": 2}
d2 = d1.copy
d2["c"] = 3
print(d1) # original unchanged
print(d2)
Output:
{'a': 1, 'b': 2}
{'a': 1, 'b': 2, 'c': 3}
7.12 pop, Remove and return value for key
Syntax: dict.pop(key[, default])
d = {"name": "Rahul", "age": 17, "marks": 85}
val = d.pop("age")
print(val)
print(d)
val2 = d.pop("grade", "Not found")
print(val2)
Output:
17
{'name': 'Rahul', 'marks': 85}
Not found
7.13 popitem, Remove and return last inserted pair
Syntax: dict.popitem
d = {"a": 1, "b": 2, "c": 3}
item = d.popitem
print(item)
print(d)
Output:
('c', 3)
{'a': 1, 'b': 2}
7.14 setdefault, Get value, set if key does not exist
Syntax: dict.setdefault(key[, default])
d = {"name": "Rahul", "age": 17}
# Key exists -- return its value
val = d.setdefault("name", "Unknown")
print(val)
print(d)
# Key does not exist -- add it with default
val2 = d.setdefault("marks", 0)
print(val2)
print(d)
Output:
Rahul
{'name': 'Rahul', 'age': 17}
0
{'name': 'Rahul', 'age': 17, 'marks': 0}
7.15 max, min, sorted on Dictionaries
These operate on keys by default.
d = {"banana": 30, "apple": 50, "cherry": 20}
print(max(d)) # cherry (max key alphabetically)
print(min(d)) # apple (min key alphabetically)
print(sorted(d)) # ['apple', 'banana', 'cherry']
# To work with values:
print(max(d.values)) # 50
print(min(d.values)) # 20
# Key with maximum value:
print(max(d, key=d.get)) # apple (key whose value is max)
Output:
cherry
apple
['apple', 'banana', 'cherry']
50
20
apple
8. Dictionary Methods Quick Reference Table
| Method | Purpose | Returns |
|---|---|---|
len(d) |
Number of pairs | int |
d.keys |
All keys | dict_keys |
d.values |
All values | dict_values |
d.items |
All (key, value) pairs | dict_items |
d.get(key, default) |
Get value safely | value or default |
d.update(other) |
Merge dictionaries | None |
del d[key] |
Delete pair | , |
d.clear |
Remove all pairs | None |
dict.fromkeys(seq, val) |
Create with default | dict |
d.copy |
Shallow copy | dict |
d.pop(key, default) |
Remove and return value | value |
d.popitem |
Remove last pair | tuple |
d.setdefault(key, default) |
Get or set | value |
9. Nested Dictionaries
A dictionary can contain another dictionary as a value.
students = {
101: {"name": "Rahul", "marks": 85},
102: {"name": "Priya", "marks": 92},
103: {"name": "Amit", "marks": 78},
}
# Access nested values
print(students[101]["name"])
print(students[102]["marks"])
# Traverse nested dictionary
for roll, info in students.items:
print(f"Roll: {roll}, Name: {info['name']}, Marks: {info['marks']}")
Output:
Rahul
92
Roll: 101, Name: Rahul, Marks: 85
Roll: 102, Name: Priya, Marks: 92
Roll: 103, Name: Amit, Marks: 78
10. Dictionary Comprehension
Syntax: {key_expr: value_expr for item in iterable if condition}
# Squares dictionary
squares = {x: x**2 for x in range(1, 6)}
print(squares)
# Filter even keys
even_sq = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_sq)
# Swap keys and values
original = {"a": 1, "b": 2, "c": 3}
swapped = {v: k for k, v in original.items}
print(swapped)
# From two lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
name_age = {n: a for n, a in zip(names, ages)}
print(name_age)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
{1: 'a', 2: 'b', 3: 'c'}
{'Alice': 25, 'Bob': 30, 'Charlie': 35}
11. Practice Programs
Program 1: Count character frequency in string using dict
s = input("Enter a string: ")
freq = {}
for ch in s:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
for ch, count in freq.items:
print(f"'{ch}' : {count}")
Sample Run:
Enter a string: hello
'h' : 1
'e' : 1
'l' : 2
'o' : 1
Shorter version using get:
s = input("Enter a string: ")
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
for ch, count in freq.items:
print(f"'{ch}' : {count}")
Program 2: Employee name:salary, create and access
n = int(input("Enter number of employees: "))
employees = {}
for i in range(n):
name = input("Enter name: ")
salary = float(input("Enter salary: "))
employees[name] = salary
print("\nEmployee Details:")
print("-" * 25)
for name, salary in employees.items:
print(f"{name:15} : {salary:>8.2f}")
print(f"\nHighest paid: {max(employees, key=employees.get)}")
print(f"Total salary: {sum(employees.values):.2f}")
Sample Run:
Enter number of employees: 3
Enter name: Alice
Enter salary: 50000
Enter name: Bob
Enter salary: 60000
Enter name: Charlie
Enter salary: 45000
Employee Details:
-------------------------
Alice : 50000.00
Bob : 60000.00
Charlie : 45000.00
Highest paid: Bob
Total salary: 155000.00
Program 3: Student roll:name:marks, filter marks > 75
students = {
101: {"name": "Rahul", "marks": 85},
102: {"name": "Priya", "marks": 72},
103: {"name": "Amit", "marks": 90},
104: {"name": "Sneha", "marks": 65},
105: {"name": "Vikram", "marks": 78},
}
print("Students with marks > 75:")
print("-" * 35)
for roll, info in students.items:
if info["marks"] > 75:
print(f"Roll: {roll}, Name: {info['name']}, Marks: {info['marks']}")
Output:
Students with marks > 75:
-----------------------------------
Roll: 101, Name: Rahul, Marks: 85
Roll: 103, Name: Amit, Marks: 90
Roll: 105, Name: Vikram, Marks: 78
Program 4: Merge two dictionaries
d1 = {"a": 1, "b": 2, "c": 3}
d2 = {"c": 30, "d": 4, "e": 5}
# Method 1: Using update
merged = d1.copy # don't modify original
merged.update(d2)
print("Merged:", merged)
# Method 2: Using ** unpacking (Python 3.5+)
merged2 = {**d1, **d2}
print("Merged:", merged2)
# Method 3: Using | operator (Python 3.9+)
merged3 = d1 | d2
print("Merged:", merged3)
Output:
Merged: {'a': 1, 'b': 2, 'c': 30, 'd': 4, 'e': 5}
Merged: {'a': 1, 'b': 2, 'c': 30, 'd': 4, 'e': 5}
Merged: {'a': 1, 'b': 2, 'c': 30, 'd': 4, 'e': 5}
Note: When keys overlap, the second dictionary's values take precedence.
Program 5: Invert a dictionary (swap keys and values)
original = {"a": 1, "b": 2, "c": 3}
inverted = {}
for key, val in original.items:
inverted[val] = key
print("Original:", original)
print("Inverted:", inverted)
Output:
Original: {'a': 1, 'b': 2, 'c': 3}
Inverted: {1: 'a', 2: 'b', 3: 'c'}
Using comprehension:
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items}
print("Inverted:", inverted)
Caution: If values are not unique, some entries will be lost when inverted.
Program 6: Word frequency counter
text = input("Enter a sentence: ")
words = text.lower.split
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
print("\nWord Frequencies:")
for word, count in freq.items:
print(f" '{word}' : {count}")
# Most common word
most_common = max(freq, key=freq.get)
print(f"\nMost common word: '{most_common}' ({freq[most_common]} times)")
Sample Run:
Enter a sentence: the cat sat on the mat the cat
Word Frequencies:
'the' : 3
'cat' : 2
'sat' : 1
'on' : 1
'mat' : 1
Most common word: 'the' (3 times)
Program 7: Phone book (add, search, delete, display)
phonebook = {}
while True:
print("\n--- Phone Book ---")
print("1. Add Contact")
print("2. Search Contact")
print("3. Delete Contact")
print("4. Display All")
print("5. Exit")
choice = input("Enter choice (1-5): ")
if choice == "1":
name = input("Enter name: ")
phone = input("Enter phone: ")
phonebook[name] = phone
print(f"Contact '{name}' added.")
elif choice == "2":
name = input("Enter name to search: ")
if name in phonebook:
print(f"{name}: {phonebook[name]}")
else:
print("Contact not found.")
elif choice == "3":
name = input("Enter name to delete: ")
if name in phonebook:
del phonebook[name]
print(f"Contact '{name}' deleted.")
else:
print("Contact not found.")
elif choice == "4":
if phonebook:
print("\nAll Contacts:")
for name, phone in phonebook.items:
print(f" {name}: {phone}")
else:
print("Phone book is empty.")
elif choice == "5":
print("Goodbye!")
break
else:
print("Invalid choice.")
Sample Run:
--- Phone Book ---
1. Add Contact
2. Search Contact
3. Delete Contact
4. Display All
5. Exit
Enter choice (1-5): 1
Enter name: Rahul
Enter phone: 9876543210
Contact 'Rahul' added.
--- Phone Book ---
...
Enter choice (1-5): 4
All Contacts:
Rahul: 9876543210
12. Common Mistakes
| Mistake | Why it is wrong | Correct way |
|---|---|---|
d["key"] for missing key |
Raises KeyError | Use d.get("key") or check with in |
| Using list as key | Lists are mutable/unhashable | Use tuple as key instead |
d = {} vs d = set |
{} is empty dict, not empty set |
Use set for empty set |
| Modifying dict while iterating | RuntimeError | Iterate over list(d.keys) or create new dict |
| Assuming dict order in old Python | Before 3.7, order was not guaranteed | Use Python 3.7+ or OrderedDict |
d1 = d2 expecting a copy |
Creates alias (same object) | Use d2 = d1.copy |
$1$2 Quick Tips
-
d[key]vsd.get(key)is asked almost every year. Know thatd[key]raises KeyError,d.get(key)returns None. -
Keys must be immutable and unique. Lists cannot be keys. If duplicate keys are given, the last value wins.
-
keys,values,items, know what each returns.itemsreturns tuples of (key, value). -
Dictionary comprehension is becoming more common in recent papers.
-
Traversal with
for key in diterates over keys by default (not values). -
Nested dictionary programs (like student records) are common 4-5 mark questions.
-
updatemerges dictionaries, if keys overlap, the updating dictionary's values win. -
popvsdel:popreturns the removed value and allows a default;delreturns nothing and raises KeyError if key missing. -
setdefaultis tricky, it returns the value if key exists, otherwise sets and returns the default. Examiners like this one.
Prefer watching over reading?
Subscribe for free.