A dictionary is a collection of key-value pairs, similar to a hashmap. Dictionaries are mutable which means that elements can be added, modified, and removed. Keys must be immutable and hashable (like strings, numbers, or tuples), while values can be of any type, including mutable types like lists.
Dictionary keys must be unique. If the same key is specified multiple times, the last value will overwrite previous values.
Note
Keys must be hashable (immutable) types. Strings, numbers, and tuples (containing hashable elements) can be used as keys, but not lists or other dictionaries.
The .get(key, default=None) method returns the value associated with the given key. If the key is not present, it returns the default value (or None if no default is specified) instead of raising an error:
Values can be added or modified by assigning to a key using square brackets. If the key doesn’t exist, it will be added; if it exists, its value will be updated:
The .pop(key[, default]) method removes the item associated with the key and returns its value. If the key is not present, it returns the default value (if specified) or raises a KeyError:
1
weather = {"weather": "rainy", "temp": "-2.0C"}
2
3
value = weather.pop("weather")
4
print(value) # rainy
5
print(weather) # {'temp': '-2.0C'}
6
7
# With default value
8
value = weather.pop("humidity", "unknown")
9
print(value) # unknown (key didn't exist, returned default)
10
11
# Without default (raises KeyError if key doesn't exist)
12
value = weather.pop("humidity") # KeyError: 'humidity'
Dictionary keys must be immutable and hashable for several important reasons:
Hash Function: Dictionaries use a hash function to quickly locate values. The hash function generates a unique hash code for each key based on its value. If a key could change after being used, its hash would change, and the dictionary wouldn’t be able to find the value associated with that key.
Consistency: If a key could change, it would create ambiguity. For example, if a key initially maps to value A, then the key changes—should it still map to value A, or should it map to something else? The dictionary wouldn’t know how to handle this.
Exercise 1: Create a dictionary with squared values
Create a dictionary such that the keys are from 1 to 10 and for each key x, the value is x**2. Print the dictionary.
Squared Dictionary
Answer:
1
d = {}
2
for x inrange(1, 11):
3
d[x] = x **2
4
print(d)
Exercise 2: Merge two dictionaries
Write a program that reads the number of key-value pairs for the first dictionary, then reads each key-value pair, then reads the number of key-value pairs for the second dictionary, then reads each key-value pair, and creates a new dictionary that is the concatenation (merge) of both dictionaries. If there are duplicate keys, the values from the second dictionary should overwrite those from the first. Print the merged dictionary.
Merge Dictionaries
Answer:
1
n1 =int(input())
2
dict1 = {}
3
for i inrange(n1):
4
key =input()
5
value =input()
6
dict1[key] = value
7
8
n2 =int(input())
9
dict2 = {}
10
for i inrange(n2):
11
key =input()
12
value =input()
13
dict2[key] = value
14
15
merged = dict1.copy()
16
merged.update(dict2)
17
print(merged)
Exercise 3: Convert dictionary values to joined strings
Given a dictionary where values are lists of strings, write a program that converts the dictionary into a list of strings where each string is the values from each key joined together. For example, given {"a": ["A", "B"], "b": ["C", "D"]}, the output should be ["AB", "CD"].
Join Dictionary Values
Answer:
1
D = {"a": ["A", "B"], "b": ["C", "D"]}
2
result = []
3
for key in D:
4
joined ="".join(D[key])
5
result.append(joined)
6
print(result)
Exercise 4: What is the output of the following code
What is the output of the following code:
1
D = {1: 1, 2: '2', '1': 1, '2': 3}
2
D['1'] =2
3
print(D[D[D[str(D[1])]]])
Answer:
The output is: 3
Let’s trace through step by step:
D = {1: 1, 2: '2', '1': 1, '2': 3} - Creates a dictionary with mixed key types (integer and string keys)
D['1'] = 2 - Updates the value for key '1' from 1 to 2, so D = {1: 1, 2: '2', '1': 2, '2': 3}
Now evaluating D[D[D[str(D[1])]]]:
D[1] = 1 (gets value for integer key 1)
str(D[1]) = str(1) = '1' (converts to string)
D[str(D[1])] = D['1'] = 2 (gets value for string key '1')
D[D[str(D[1])]] = D[2] = '2' (gets value for integer key 2, which is the string '2')
D[D[D[str(D[1])]]] = D['2'] = 3 (gets value for string key '2')
So the final output is 3.
Exercise 5: What is the output of the following code
What is the output of the following code:
1
D =dict()
2
for i inrange(3):
3
for j inrange(2):
4
D[i] = j
5
print(D)
Answer:
The output is: {0: 1, 1: 1, 2: 1}
Let’s trace through the nested loops:
i = 0:
j = 0: D[0] = 0
j = 1: D[0] = 1 (overwrites previous value)
i = 1:
j = 0: D[1] = 0
j = 1: D[1] = 1 (overwrites previous value)
i = 2:
j = 0: D[2] = 0
j = 1: D[2] = 1 (overwrites previous value)
So the final dictionary is {0: 1, 1: 1, 2: 1}.
Exercise 6: Count frequency of characters
Write a program that reads a string and counts the frequency of each character using a dictionary. Print each character and its count on a separate line in the order they first appear.
Character Frequency
Answer:
1
text =input()
2
freq = {}
3
for char in text:
4
if char in freq:
5
freq[char] +=1
6
else:
7
freq[char] =1
8
9
for char in text:
10
if freq[char] >0:
11
print(f"{char}{freq[char]}")
12
freq[char] =0
Exercise 7: Invert a dictionary
Write a program that reads a dictionary size, then reads key-value pairs, and creates a new dictionary where keys and values are swapped. If there are duplicate values in the original dictionary, the last key should be used.
Invert Dictionary
Answer:
1
n =int(input())
2
d = {}
3
for i inrange(n):
4
key =input()
5
value =input()
6
d[key] = value
7
8
inverted = {}
9
for key, value in d.items():
10
inverted[value] = key
11
12
print(inverted)
Exercise 8: Find keys with maximum value
Write a program that reads a dictionary size, then reads key-value pairs (where values are integers), and finds all keys that have the maximum value. Print the keys on separate lines.
Keys with Max Value
Answer:
1
n =int(input())
2
d = {}
3
for i inrange(n):
4
key =input()
5
value =int(input())
6
d[key] = value
7
8
max_value =max(d.values())
9
for key, value in d.items():
10
if value == max_value:
11
print(key)
Exercise 9: Dictionary from two lists
Write a program that reads the size n, then reads n keys, then reads n values, and creates a dictionary from these two lists where the i-th key is paired with the i-th value.
Dictionary from Lists
Answer:
1
n =int(input())
2
keys = []
3
for i inrange(n):
4
keys.append(input())
5
values = []
6
for i inrange(n):
7
values.append(input())
8
9
d = {}
10
for i inrange(n):
11
d[keys[i]] = values[i]
12
13
print(d)
Exercise 10: Remove all keys with even values
Write a program that reads a dictionary size, then reads key-value pairs (where values are integers), and removes all keys whose values are even numbers. Print the modified dictionary.