Dictionaries in Python
Dictionaries in Python
In lists, where there is an order associated with the data items because they act as storage units
for other objects or variables created. Dictionaries are different from lists and tuples because the
group of objects they hold are not in any particular order, but rather each object has its own
unique name, commonly known as a key.
1. Dictionaries are Unordered : The dictionary elements (key-value pairs) are not in ordered
form.
2. Dictionary Keys are Case Sensitive : The same key name but with different case are
treated as different keys in Python dictionaries.
3. No duplicate key is allowed : When duplicate keys encountered during assignment, the
last assignment wins.
4. Keys must be immutable : We can use strings, numbers or tuples as dictionary keys but
something like [‘key’] is not allowed.
Answer
Dictionaries can be changed by adding new key-value pairs and by deleting or changing the
existing ones. Hence they are called as mutable types.
For example:
d = {"a" : 1 , "b" : 2}
d["c"] = 3
d["b"] = 4
del d["a"]
print(d)
Output
{'b': 4, 'c': 3}
Answer
1. By using curly brackets and separating key-value pairs with commas as per the syntax below:
For example:
2. By using dictionary constructor dict(). There are multiple ways to provide keys and values to
dict() constructor:
Employee = dict(zip(('name','salary','age'),('John',10000,24)))
Output
{'name': 'John', 'salary': 10000, 'age': 24}
Answer
A dictionary can have values of all data types i.e., integers, floats, strings, booleans, sequences
and collections, etc. For example:
d = {1:'a' , 2: 2 , 3: True , 4: 3.5 , 5: "python",(1,2,3) : 4}
Answer : Individual elements of a dictionary can be accessed by using their corresponding keys
as per the syntax shown below:
<dictionary-name> [<key>]
For example:
In addition to this, we can also use the get( ) method to get value of the given key as per the
syntax shown below:
<dictionary-name>.get(<key>, [default])
For example:
Answer : In lists or strings, the elements are accessed through their index where as in
dictionaries, the elements are accessed through the keys defined in the key:value pairs.
Moreover, lists and strings are ordered set of elements but dictionaries are unordered set of
elements so its elements cannot be accessed as per specific order.
Question : What do you understand by ordered collection and unordered collection ? Give
examples.
Answer : Ordered Collection is the one in which the position of each element is fixed.
Example: List, strings, Tuples
Unordered Collection is the one in which position of each element is not fixed i.e., the order of
all the elements are not maintained.
Example: Sets, Dictionaries
Answer
There are three ways by which new key:value pairs can be added to an existing dictionary:
1. By using assignment as per the following syntax:
<dictionary>[<key>] = <value>
For example:
d = {1 : 'a' , 2 : 'b'}
d[3] = 'c'
print(d)
Output
<dictionary>.update(<other-dictionary>)
For example:
d = {1 : 'a' , 2 : 'b'}
d.update({3 : 'c'})
print(d)
Output
Question : Can you remove key:value pairs from a dictionary and if so, how?
Answer : Yes, key:value pairs can be removed from a dictionary. The different methods to
remove key:value pairs are given below:
del <dictionary>[<key>]
For example:
<dict>.pop(key, <value>)
For example:
dict = {'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'}
dict.pop("tuple")
print(dict)
Output
{'list': 'mutable', 'dictionary': 'mutable'}
3. popitem() method:
This method removes and returns the last inserted item in the dictionary. It is used as per the
syntax:
<dict>.popitem()
For example:
Here, the last element of dict was 'dictionary': 'mutable' which gets removed by function
popitem().
Question : Dictionary is a mutable type, which means you can modify its contents ? What
all is modifiable in a dictionary ? Can you modify the keys of a dictionary ?
Answer : Yes, we can modify the contents of a dictionary. Values of key-value pairs are
modifiable in dictionary. New key-value pairs can also be added to an existing dictionary and
existing key-value pairs can be removed.
However, the keys of the dictionary cannot be changed. Instead we can add a new key : value
pair with the desired key and delete the previous one.
For example:
d = { 1 : 1 }
d[2] = 2
print(d)
d[1] = 3
print(d)
d[3] = 2
print(d)
del d[2]
print(d)
Output
{1: 1, 2: 2}
{1: 3, 2: 2}
{1: 3, 2: 2, 3: 2}
{1: 3, 3: 2}
Explanation
Answer : The clear( ) function removes all the key:value pairs from the dictionary and makes
it empty dictionary while del <dict> statement removes the complete dictionary as an object.
After del statement with a dictionary name, that dictionary object no more exists, not even empty
dictionary.
For example:
Answer
pop( ) popitem( )
pop( ) removes the item with the specified popitem( ) removes the last inserted item from the
key name. dictionary.
With pop( ), we can specify a return value With popitem( ), we cannot specify any such
or a message if the given key is not found message/return value while deleting from an empty
in the dictionary. dictionary. It will raise an error in this case.
Answer
The copy() function is used to create a shallow copy of a dictionary where only a copy of keys is
created and the values referenced are shared by the two copies.
For example:
Here, original_d and new_d are two isolated objects, but their contents still share the same
reference i.e ('a','b')
Question : The following code is giving some error. Find out the error and correct it.
d1 = {"a" : 1, 1 : "a", [1, "a"] : "two"}
Answer
This type of error occurs when a mutable type is used as a key in dictionary. In d1, [1, "a"] is
used as a key which is a mutable type of list. It will generate the below error:
This error can be fixed by using a tuple as a key instead of list as shown below:
Question : The following code has two dictionaries with tuples as keys. While one of these
dictionaries being successfully created, the other is giving some error. Find out which
dictionary will be created successfully and which one will give error and correct it :
Answer
dict1 will be created successfully because tuples are used as keys. As tuples are immutable,
therefore it won't give any error.
dict2 will give an error because the tuples used as keys of dict2 contain lists as their elements. As
lists are mutable, so they can't appear in keys of the dictionary.
It can be corrected by removing list elements from the tuples as shown below:
dict2 = { (1,2) : [1,2], (3,4) : [3, 4]}
Answer
Output
dict_keys([5, 'a'])
dict_values([[6, 7, 8], (1, 2, 3)])
Explanation
keys() function returns all the keys defined in the dictionary in the form of a list. values()
function returns all the values defined in the dictionary in the form of a list.
Question : Consider the following code and then answer the questions that follow :
Answer
Answer
Output
Dictionary contents
5 : number numbernumbernumber
a : string stringstringstring
5 number numbernumbernumber
a string stringstringstring
Question : Write a program to enter names of employees and their salaries as input and
store them in a dictionary.
Solution
d = {}
ans = "y"
while ans == "y" or ans == "Y" :
name = input("Enter employee name: ")
sal = float(input("Enter employee salary: "))
d[name] = sal
ans = input("Do you want to enter more employee names? (y/n)")
print(d)
Output
Enter employee name: Kavita
Enter employee salary: 35250.50
Do you want to enter more employee names? (y/n)y
Enter employee name: Rakesh
Enter employee salary: 27000
Do you want to enter more employee names? (y/n)n
{'Kavita': 35250.5, 'Rakesh': 27000.0}
Question : Write a program to count the number of times a character appears in a given
string.
Solution
str = input("Enter the string: ")
ch = input("Enter the character to count: ");
c = str.count(ch)
Question : Write a program to convert a number entered by the user into its
corresponding number in words. For example, if the input is 876 then the output should be
'Eight Seven Six'.
(Hint. use dictionary for keys 0-9 and their values as equivalent words.)
Solution
num = int(input("Enter a number: "))
d = {0 : "Zero" , 1 : "One" , 2 : "Two" , 3 : "Three" , 4 : "Four" , 5 :
"Five" , 6 : "Six" , 7 : "Seven" , 8 : "Eight" , 9 : "Nine"}
digit = 0
str = ""
while num > 0:
digit = num % 10
num = num // 10
str = d[digit] + " " + str
print(str)
Output
Enter a number: 589
Five Eight Nine
Question : Repeatedly ask the user to enter a team name and how many games the team
has won and how many they lost. Store this information in a dictionary where the keys are
the team names and the values are lists of the form [wins, losses].
(a) Using the dictionary created above, allow the user to enter a team name and print out the
team's winning percentage.
(b) Using the dictionary, create a list whose entries are the number of wins of each team.
(c) Using the dictionary, create a list of all those teams that have winning records.
Solution
d = {}
ans = "y"
while ans == "y" or ans == "Y" :
name = input("Enter Team name: ")
w = int(input("Enter number of wins: "))
l = int(input("Enter number of losses: "))
d[name] = [w, l]
ans = input("Do you want to enter more team names? (y/n): ")
w_team = []
for i in d.values():
w_team.append(i[0])
w_rec = []
for i in d:
if d[i][0] > 0:
w_rec.append(i)
Question : Write a program that repeatedly asks the user to enter product names and
prices. Store all of these in a dictionary whose keys are the product names and whose
values are the prices.
When the user is done entering products and prices, allow them to repeatedly enter a product
name and print the corresponding price or a message if the product is not in the dictionary.
Solution
d = {}
ans = "y"
while ans == "y" or ans == "Y" :
p_name = input("Enter the product name: ")
p_price = float(input("Enter product price: "))
d[p_name] = p_price
ans = input("Do you want to enter more product names? (y/n): ")
ans = "y"
while ans == "y" or ans == "Y" :
p_name = input("Enter the product name to search: ")
print("Price:", d.get(p_name, "Product not found"))
ans = input("Do you want to know price of more products? (y/n): ")
Output
Enter the product name: apple
Enter product price: 165.76
Do you want to enter more product names? (y/n): y
Enter the product name: banana
Enter product price: 75
Do you want to enter more product names? (y/n): y
Enter the product name: guava
Enter product price: 48.5
Do you want to enter more product names? (y/n): n
Enter the product name to search: apple
Price: 165.76
Do you want to know price of more products? (y/n): y
Enter the product name to search: tomato
Price: Product not found
Do you want to know price of more products? (y/n): n
Question : Can you store the details of 10 students in a dictionary at the same time ?
Details include - rollno, name, marks, grade etc.
Solution
n = 10
details = {}
for i in range(n):
name = input("Enter the name of student: ")
roll_num = int(input("Enter the roll number of student: "))
marks = int(input("Enter the marks of student: "))
grade = input("Enter the grade of student: ")
details[roll_num] = [name, marks, grade]
print()
print(details)
Output
Enter the name of student: Sushma
Enter the roll number of student: 4
Enter the marks of student: 56
Enter the grade of student: C
{4: ['Sushma', 56, 'C'], 3: ['Sanjana', 76, 'B+'], 45: ['Manika', 45, 'D'],
1: ['Mitanshu', 23, 'F'], 7: ['Anshika', 77, 'B'], 9: ['Purva', 99, 'A+'], 2:
['Priyanka', 89, 'A'], 6: ['Anand', 100, 'A+'], 10: ['Sarika', 55, 'B+']}