Question 1
Why are dictionaries called mutable types?
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}
dict["c"] = 3 adds a new key-value pair to dict.
dict["b"] = 4 changes existing key-value pair in dict.
del dict["a"] removes the key-value pair "a" : 1
Question 2
What are different ways of creating dictionaries?
Answer
The different ways of creating dictionaries in Python are:
1. By using curly brackets and separating key-value pairs with commas as per the syntax below:
<dictionary-name> = {<key>:<value>, <key>:<value>...}
For example:
d = {'a': 1, 'b': 2, 'c': 3}
2. By using dictionary constructor dict(). There are multiple ways to provide keys and values to
dict() constructor:
i. Specifying key:value pairs as keyword arguments to dict() function:
For example:
Employee = dict(name = 'john' , salary = 1000, age = 24)
print(Employee)
Output
{'name': 'john', 'salary': 1000, 'age': 24}
ii. Specifying comma separated key:value pairs:
Key:value pairs are enclosed in curly braces in this format.
For example:
Employee = dict({'name': 'john', 'salary': 1000, 'age': 24})
Output
{'name': 'john', 'salary': 1000, 'age': 24}
iii. Specifying keys and its corresponding values separately:
Keys and Values are enclosed separately in parentheses and are given as arguments to zip()
function.
For example:
Employee = dict(zip(('name','salary','age'),('John',10000,24)))
Output
{'name': 'John', 'salary': 10000, 'age': 24}
iv. Specifying key:value pairs separately in form of sequences:
One list or tuple that contains lists/tuples of individual key:value pairs is passed as an argument
to dict().
For example:
Employee = dict([['name','John'],['salary',10000],['age',24]])
print(Employee)
Output
{'name': 'John', 'salary': 10000, 'age': 24}
3. By using fromkeys() function:
fromkeys() function is used to create a new dictionary from a sequence containing all the keys
and a common value, which will be assigned to all the keys.
For example:
x = ('list', 'set', 'dictionary')
y = 'mutable'
my_dict = [Link](x, y)
print(my_dict)
Output
{'list': 'mutable', 'set': 'mutable', 'dictionary': 'mutable'}
Question 3
What values can we have in a dictionary?
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}
Question 4
How are individual elements of dictionaries accessed?
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:
d = {'a': 1, 'b': 2, 'c': 3}
print(d['a'])
Output
1
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:
d = {'a': 1, 'b': 2, 'c': 3}
print([Link]('a'))
Output
Question 5
How is indexing of a dictionary different from that of a list or a string?
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 6
Which of the following types qualify to be the keys of a dictionary?
1. String
2. tuple
3. Integer
4. float
5. list
6. dictionary
Answer
The following types can be used as keys of a dictionary because they are immutable:
1. String
2. tuple
3. Integer
4. float
As lists and dictionaries are mutable so they cannot be used as keys of a dictionary.
Question 7
Can you change an element of a sequence or collection? What if a collection is a dictionary?
What if a sequence is a string?
Answer
Elements of a collection or sequence can be changed only if the collection or sequence is
mutable. Hence, for dictionaries, the elements can be changed as dictionaries are mutable but for
strings is cannot be changed as strings are immutable.
Example:
>>> d = {1 : 'a', 2: 'b'}
>>> d[1] = 'c'
>>> str = "hello"
>>> str[1] = "python"
Output
{1: 'c', 2: 'b'}
TypeError: 'str' object does not support item assignment
Question 8
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
Question 9
How do you add key:value pairs to an existing dictionary?
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
{1: 'a', 2: 'b', 3: 'c'}
2. By using update() method:
update() method merges key:value pairs from new dictionary into the original dictionary adding
or replacing as needed. The syntax to use this method is:
<dictionary>.update(<other-dictionary>)
For example:
d = {1 : 'a' , 2 : 'b'}
[Link]({3 : 'c'})
print(d)
Output
{1: 'a', 2: 'b', 3: 'c'}
3. Using setdefault() method:
It inserts a new key:value pair only if the key doesn't already exist. If the key already exists, it
returns the current value of the key. The syntax to use this method is:
<dictionary>.setdefault(<key>,<value>)
For example:
d = {1 : 'a' , 2 : 'b'}
[Link](3,'c')
print(d)
Output
{1: 'a', 2: 'b', 3: 'c'}
Question 10
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:
1. By using del command:
It is used to delete an item with the specified key name. The syntax for doing so is as given
below:
del <dictionary>[<key>]
For example:
dict = {'list': 'mutable', 'tuple': 'immutable', 'dictionary':
'mutable'}
del dict["tuple"]
print(dict)
Output
{'list': 'mutable', 'dictionary': 'mutable'}
2. By using pop() method:
This method removes and returns the dicitionary element associated to the passed key. It is used
as per the syntax:
<dict>.pop(key, <value>)
For example:
dict = {'list': 'mutable', 'tuple': 'immutable', 'dictionary':
'mutable'}
[Link]("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:
dict = {'list': 'mutable', 'tuple': 'immutable', 'dictionary':
'mutable'}
[Link]()
print(dict)
Output
{'list': 'mutable', 'tuple': 'immutable'}
Here, the last element of dict was 'dictionary': 'mutable' which gets removed by function
popitem().
Multiple Choice Questions
Question 1
Dictionaries are ............... set of elements.
1. sorted
2. ordered
3. unordered
4. random
Answer
unordered
Reason — Dictionary are unordered set of elements because it stores data as key-value pair and
the pair of object they hold aren't indexed implicitly, that means we cannot refer to an item by
using an index.
Question 2
Dictionaries are also called ...............
1. mappings
2. hashes
3. associative arrays
4. all of these
Answer
all of these
Reason — Dictionaries are called as:
1. mappings because a dictionary represents a mapping from keys to values that means each
key "maps to" a value.
2. hashes because the keys of a dictionary in python are generated internally by a hashing
function.
3. Associative arrays because it is an abstract data type that can also holds data in (key,
value) pairs just like physical dictionary.
Question 3
Dictionaries are ............. data types of Python.
1. mutable
2. immutable
3. simple
4. all of these
Answer
mutable
Reason — Dictionaries are mutable data types of Python since its entries can be added,
removed, and changed in place.
Question 4
Which of the following functions will return the key, value pairs of a dictionary ?
1. keys( )
2. values( )
3. items( )
4. all of these
Answer
items( )
Reason — items() method is used to return the list with all dictionary keys with values.
For example:
d = {'a':2, 'b':5}
print([Link]())
Output
dict_items([('a', 2), ('b', 5)])
Question 5
Which of the following will add a key to the dictionary only if it does not already exist in the
dictionary ?
1. fromkeys( )
2. update( )
3. setdefault( )
4. all of these
Answer
setdefault()
Reason — setdefault() function is used to return the value of a key (if the key is in dictionary).
Else, it inserts a key with the default value to the dictionary.
For example:
d = {"list": "mutable","tuple": "immutable"}
[Link]("dictionaries", "mutable")
Output
mutable
Since "dictionaries" named key does not exist in dict, therefore setdefault() function inserts it to
the dictionary d and returns the value of it.
Question 6
Which of the following will create a dictionary with given keys and a common value ?
1. fromkeys( )
2. update( )
3. setdefault( )
4. all of these
Answer
fromkeys( )
Reason — fromkeys() function is used to create a new dictionary from a sequence containing all
the keys and a common value, which will be assigned to all the keys.
For example:
x = ('list', 'set', 'dictionary')
y = 'mutable'
my_dict = [Link](x, y)
print(my_dict)
Output
{'list': 'mutable', 'set': 'mutable', 'dictionary': 'mutable'}
Question 7
Which value is assigned to keys, if no value is specified with the fromkeys() method ?
1. 0
2. 1
3. None
4. any of these
Answer
None
Reason — If no value is specified, the keys are assigned None as their default values.
Question 8
Which of the following can be used to delete item(s) from a dictionary?
1. del statement
2. pop( )
3. popitem( )
4. all of these
Answer
all of these
Reason —
1. del keyword is used to delete an item with the specified key name.
For example:
d = {'list': 'mutable', 'tuple': 'immutable', 'dictionary':
'mutable'}
del dict["tuple"]
print(d)
Output
{'list': 'mutable', 'dictionary': 'mutable'}
del keyword deletes the key "tuple" and it's corresponding value.
2. pop() method removes the item with the specified key name: For example:
d = {'list': 'mutable', 'tuple': 'immutable', 'dictionary':
'mutable'}
[Link]("tuple")
print(d)
Output
{'list': 'mutable', 'dictionary': 'mutable'}
The key named "tuple" is popped out. Hence dictionary d has only two key-value pairs.
3. popitem() method removes the last inserted item of dictionary.
For example:
d = {'list': 'mutable', 'tuple': 'immutable', 'dictionary':
'mutable'}
[Link]()
print(d)
Output
{'list': 'mutable', 'tuple': 'immutable'}
Here, the last element of d was 'dictionary': 'mutable' which gets removed by function
popitem().
Question 9
Which of the following will raise an error if the given key is not found in the dictionary ?
1. del statement
2. pop( )
3. popitem()
4. all of these
Answer
del statement
Reason — For example:
d = {'list': 'mutable', 'tuple': 'immutable'}
del d['dictionary']
Output
<module> KeyError: 'dictionary'
Since key named "dictionary" does not exist in d, del keyword will raise an error.
Question 10
Which of the following will raise an error if the given dictionary is empty ?
1. del statement
2. pop( )
3. popitem( )
4. all of these
Answer
popitem()
Reason — Calling popitem() method on an empty dictionary will throw a KeyError.
For example:
d = {}
[Link]()
Output
KeyError: 'popitem(): dictionary is empty'
Question 11
A copy of the dictionary where only the copy of the keys is created for the new dictionary, is
called ............... copy.
1. key copy
2. shallow copy
3. deep copy
4. partial copy
Answer
shallow copy
Reason — Shallow copy means the content of the dictionary is not copied by value, but just
creating a new reference. It is done by using copy() function on original dictionary.
For example:
original_dict = {1:'computer with python', 2:'computer with
java'}
new_dict = original_dict.copy()
print(new_dict)
Output
{1: 'computer with python', 2: 'computer with java'}
Question 12
A copy of the dictionary where the copy of the keys as well as the values is created for the new
dictionary, is called ............... copy.
1. key copy
2. shallow copy
3. deep copy
4. partial copy
Answer
deep copy
Reason — A deep copy constructs a new compound object and then, recursively, inserts copies
into it of the objects found in the original.
Question 13
Which of the following is correct with respect to above Python code ?
d = {"a" : 3,"b" : 7}
1. a dictionary d is created.
2. a and b are the keys of dictionary d.
3. 3 and 7 are the values of dictionary d.
4. All of these.
Answer
All of these.
Reason — The dictionary d has two key-value pairs where a and b are the keys and 3 and 7 are
the values respectively. Therefore, all the statements are correct.
Question 14
What would the following code print ?
d = {'spring':'autumn','autumn':'fall','fall':'spring'}
print(d['autumn'])
1. autumn
2. fall
3. spring
4. Error
Answer
fall
Reason — The values of dictionaries can be accessed by giving the key inside the square
brackets of dictionary. The expression d['autumn'] will return "fall" as autumn is the key of
dictionary d so d['autumn'] will return its value i.e., "fall".
Question 15
What is printed by the following statements ?
D1 = {"cat":12,"dog":6,"elephant":23,"bear":20}
print("dog" in D1)
1. True
2. False
3. Error
4. None
Answer
True
Reason — in operator is used to check whether a certain key is in the dictionary or not. It is also
called containment check. It returns a boolean value.
Here, the expression "dog" in D1 will print true, since D1 contains "dog" key.
Question 16
What is printed by the following statements ?
D1 = {"cat":12,"dog":6,"elephant":23,"bear":20}
print(25 in D1)
1. True
2. False
3. Error
4. None
Answer
False
Reason — in operator is used to check whether a certain key is in the dictionary or not. It is also
called containment check. It returns a boolean value.
Here, the expression 25 in D1 will print false, since D1 does not contain 25 key.
Question 5
Can you change the order of dictionary's contents, i.e., can you
sort the contents of a dictionary ?
Answer
No, the contents of a dictionary cannot be sorted in place like
that of a list. However, we can indirectly sort the keys and
values of a dictionary by using sorted() function:
sorted([Link]())
sorted([Link]())
sorted(dictionary)
sorted([Link]())
For example:
>>> d = {"def" : 2 ,"abc" : 1, "mno" : 3}
>>> sorted([Link]())
>>> sorted([Link]())
>>> sorted(d)
>>> sorted([Link]())
Output
['abc', 'def', 'mno']
[1, 2, 3]
['abc', 'def', 'mno']
[('abc', 1), ('def', 2), ('mno', 3)]
Question 11
What does fromkeys( ) method do?
Answer
The fromkeys() method is used to create a new dictionary from a sequence containing all the
keys and a common value, which will be assigned to all the keys as per syntax shown below:
[Link](<keys sequence>, [<value>])
For example:
x = ('list', 'set', 'dictionary')
y = 'mutable'
my_dict = [Link](x, y)
print(my_dict)
Output
{'list': 'mutable', 'set': 'mutable', 'dictionary': 'mutable'}
Question 12
How is pop( ) different from popitem( ) ?
Answer
The differences between pop( ) and popitem( ) are mentioned below:
pop( ) popitem( )
pop( ) removes the item with the popitem( ) removes the last inserted item from the
specified key name. dictionary.
With pop( ), we can specify a return With popitem( ), we cannot specify any such
value or a message if the given key is message/return value while deleting from an empty
not found in the dictionary. dictionary. It will raise an error in this case.
Question 13
If sorted( ) is applied on a dictionary, what does it return ?
Answer
If only sorted() is applied on dictionary then it considers only the keys of the dictionary for
sorting and returns a sorted list of the dictionary keys.
For example:
d = {2 : "def" , 3 : "abc" , 1 : "mno"}
print(sorted(d))
Output
[1, 2, 3]
Question 1
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 2
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 = [Link](ch)
print("Count of character",ch,"in",str,"is :", c)
Output
Enter the string: appoggiatura
Enter the character to count: a
Count of character a in appoggiatura is : 3
Question 3
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 4
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): ")
team = input("Enter team name for winning percentage: ")
if team not in d:
print("Team not found", team)
else:
wp = d[team][0] / sum(d[team]) * 100
print("Winning percentage of", team, "is", wp)
w_team = []
for i in [Link]():
w_team.append(i[0])
print("Number of wins of each team", w_team)
w_rec = []
for i in d:
if d[i][0] > 0:
w_rec.append(i)
print("Teams having winning records are:", w_rec)
Output
Enter Team name: masters
Enter number of wins: 9
Enter number of losses: 1
Do you want to enter more team names? (y/n): y
Enter Team name: musketeers
Enter number of wins: 6
Enter number of losses: 4
Do you want to enter more team names? (y/n): y
Enter Team name: challengers
Enter number of wins: 0
Enter number of losses: 10
Do you want to enter more team names? (y/n): n
Enter team name for winning percentage: musketeers
Winning percentage of musketeers is 60.0
Number of wins of each team [9, 6, 0]
Teams having winning records are: ['masters', 'musketeers']
Question 5
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:", [Link](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 6
Create a dictionary whose keys are month names and whose values
are the number of days in the corresponding months.
(a) Ask the user to enter a month name and use the dictionary to tell
how many days are in the month.
(b) Print out all of the keys in alphabetical order.
(c) Print out all of the months with 31 days.
(d) Print out the (key-value) pairs sorted by the number of days in
each month.
Solution
days_in_months = {
"january":31,
"february":28,
"march":31,
"april":30,
"may":31,
"june":30,
"july":31,
"august":31,
"september":30,
"october":31,
"november":30,
"december":31
}
m = input("Enter name of month: ")
if m not in days_in_months:
print("Please enter the correct month")
else:
print("There are", days_in_months[m], "days in", m)
print("Months in alphabetical order are:",
sorted(days_in_months))
print("Months with 31 days:", end=" ")
for i in days_in_months:
if days_in_months[i] == 31:
print(i, end=" ")
day_month_lst = []
for i in days_in_months:
day_month_lst.append([days_in_months[i], i])
day_month_lst.sort()
month_day_lst =[]
for i in day_month_lst:
month_day_lst.append([i[1], i[0]])
sorted_days_in_months = dict(month_day_lst)
print()
print("Months sorted by days:", sorted_days_in_months)
Output
Enter name of month: may
There are 31 days in may
Months in alphabetical order are: ['april', 'august',
'december', 'february', 'january', 'july', 'june', 'march',
'may', 'november', 'october', 'september']
Months with 31 days: january march may july august october
december
Months sorted by days: {'february': 28, 'april': 30,
'june': 30, 'november': 30, 'september': 30, 'august': 31,
'december': 31, 'january': 31, 'july': 31, 'march': 31,
'may': 31, 'october': 31}
Question 7
Can you store the details of 10 students in a dictionary at the same
time ? Details include - rollno, name, marks, grade etc. Give example
to support your answer.
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
Enter the name of student: Radhika
Enter the roll number of student: 3
Enter the marks of student: 90
Enter the grade of student: A+
Enter the name of student: Manika
Enter the roll number of student: 45
Enter the marks of student: 45
Enter the grade of student: D
Enter the name of student: Mitanshu
Enter the roll number of student: 1
Enter the marks of student: 23
Enter the grade of student: F
Enter the name of student: Anshika
Enter the roll number of student: 7
Enter the marks of student: 77
Enter the grade of student: B
Enter the name of student: Purva
Enter the roll number of student: 9
Enter the marks of student: 99
Enter the grade of student: A+
Enter the name of student: Sanjana
Enter the roll number of student: 3
Enter the marks of student: 76
Enter the grade of student: B+
Enter the name of student: Priyanka
Enter the roll number of student: 2
Enter the marks of student: 89
Enter the grade of student: A
Enter the name of student: Anand
Enter the roll number of student: 6
Enter the marks of student: 100
Enter the grade of student: A+
Enter the name of student: Sarika
Enter the roll number of student: 10
Enter the marks of student: 55
Enter the grade of student: B+
{4: ['Sushma', 56, 'C'], 3: ['Sanjana', 76, 'B+'], 45:
['Manika', 45, 'D'], 1: ['Mitanshu', 23, 'F'], 7: ['Anshik