Dictionary part 2
M3-R5.1 · Chapter 5: Sequence Data Types · 6 min read
10. Dictionary Comprehension
Dictionary comprehension provides a concise way to create dictionaries from iterables or other dictionaries.
Syntax:
new_dict = {key_expr: value_expr for item in iterable if condition}
Examples:
# Squares of numbers 1 to 5
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1:1, 2:4, 3:9, 4:16, 5:25}
# Filter: only even squares
even_sq = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_sq) # {2:4, 4:16, 6:36, 8:64, 10:100}
# Swap keys and values
original = {'a': 1, 'b': 2, 'c': 3}
swapped = {v: k for k, v in original.items()}
print(swapped) # {1:'a', 2:'b', 3:'c'}
# Convert two lists into a dictionary
keys = ['name', 'age', 'city']
values = ['Alice', 21, 'Delhi']
d = {k: v for k, v in zip(keys, values)}
print(d) # {'name':'Alice', 'age':21, 'city':'Delhi'}
11. Nested Dictionaries
A dictionary can contain another dictionary as a value, creating a nested structure. This is useful for representing complex, hierarchical data.
students = {
'Alice': {'age': 21, 'marks': 95, 'grade': 'A'},
'Bob' : {'age': 22, 'marks': 88, 'grade': 'B'},
'Carol': {'age': 20, 'marks': 73, 'grade': 'C'}
}
# Accessing nested values
print(students['Alice']['marks']) # 95
print(students['Bob']['grade']) # B
# Adding a new student
students['Dave'] = {'age': 23, 'marks': 80, 'grade': 'B'}
# Iterating over nested dictionary
for name, info in students.items():
print(name, '->', info['marks'])
12. Linear Search in Dictionary
12.1 Search by Key
student = {'name': 'Alice', 'age': 21, 'grade': 'A'}
search_key = 'age'
found = False
for key in student:
if key == search_key:
found = True
print('Key found! Value:', student[key])
break
if not found:
print('Key not found')
# Output: Key found! Value: 21
12.2 Search by Value
student = {'name': 'Alice', 'age': 21, 'grade': 'A'}
search_val = 21
found = False
for key, value in student.items():
if value == search_val:
found = True
print('Value found! Key:', key)
break
if not found:
print('Value not found')
# Output: Value found! Key: age
13. Counting Frequency Using a Dictionary
Dictionaries are excellent for counting how many times each element appears in a sequence.
# Count frequency of characters in a string
text = 'hello world'
freq = {}
for ch in text:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print(freq)
# {'h':1, 'e':1, 'l':3, 'o':2, ' ':1, 'w':1, 'r':1, 'd':1}
# Shorter version using get()
freq2 = {}
for ch in text:
freq2[ch] = freq2.get(ch, 0) + 1
# Count word frequencies in a sentence ( we discuss about this after learning string functions)
sentence = 'apple banana apple cherry banana apple'
words = sentence.split()
word_freq = {}
for word in words:
word_freq[word] = word_freq.get(word, 0) + 1
print(word_freq) # {'apple':3, 'banana':2, 'cherry':1}
14. Merging Dictionaries
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d1.update(d2)
print(d1) # {'a':1, 'b':2, 'c':3, 'd':4}
15. Dictionary vs List vs Tuple
|
Feature |
Dictionary |
List |
Tuple |
|
Syntax |
{ key: value } |
[ ] |
( ) |
|
Ordered |
Yes (3.7+) |
Yes |
Yes |
|
Mutable |
Yes |
Yes |
No |
|
Indexed by |
Key (any immutable) |
Integer |
Integer |
|
Duplicates |
Keys: No, Values: Yes |
Yes |
Yes |
|
Use Case |
Key-value mapping |
Ordered items |
Fixed data |
|
Speed (lookup) |
O(1) avg. |
O(n) |
O(n) |
16. Common Errors with Dictionaries
|
Error |
Cause |
Example |
|
KeyError |
Accessing a key that does not exist |
d['city'] when 'city' not in d |
|
TypeError |
Using a mutable type (list) as a key |
d[[1,2]] = 'val' |
|
AttributeError |
Calling a wrong method name |
d.append('x') (no append in dict) |
|
TypeError |
Iterating with wrong assumption |
for i in range(len(d)): d[i] |
17. Practical Programs
17.1 Student Report Card
report = {}
n = int(input("Number of students: "))
for _ in range(n):
name = input("Name: ")
marks = float(input("Marks: "))
report[name] = marks
print("\n--- Report Card ---")
for name, marks in report.items():
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
else:
grade = "C"
print(f"{name}: {marks} -> Grade {grade}")
topper = max(report, key=report.get)
print(f"Topper: {topper} with {report[topper]} marks")
17.2 Phone Book Application
phonebook = {}
while True:
print("\n--- Phonebook Menu ---")
print("1. Add Contact")
print("2. Search Contact")
print("3. Delete Contact")
print("4. Show All Contacts")
print("5. Exit")
choice = input("Enter choice (1-5): ")
if choice == "1":
name = input("Enter name: ")
number = input("Enter number: ")
phonebook[name] = number
print(f"{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"{name} deleted.")
else:
print("Contact not found.")
elif choice == "4":
print("\n--- All Contacts ---")
for name, number in phonebook.items():
print(f"{name}: {number}")
elif choice == "5":
print("Exiting Phonebook. Goodbye!")
break
else:
print("Invalid choice. Try again.")