Professional Documents
Culture Documents
Chapter 13 Dictionaries
Chapter 13 Dictionaries
Chapter 13 Dictionaries
Dictionaries
Class 11 - Computer Science with Python Sumita Arora
Checkpoint 13.1
Question 1
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
Answer
1. By using curly brackets and separating key-value pairs with commas as per the syntax below:
Output
Output
Employee = dict(zip(('name','salary','age'),('John',10000,24)))
Output
Employee = dict([['name','John'],['salary',10000],['age',24]])
print(Employee)
Output
Output
Question 3
Answer
A dictionary can have values of all data types i.e., integers, floats, strings, booleans, sequences and collections, etc. For example:
Question 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:
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:
Output
Question 5
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
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:
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
Answer
There are three ways by which new key:value pairs can be added to an existing dictionary:
<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
<dictionary>.setdefault(<key>,<value>)
For example:
d = {1 : 'a' , 2 : 'b'}
d.setdefault(3,'c')
print(d)
Output
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:
Output
<dict>.pop(key, <value>)
For example:
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:
Output
Question 1
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
1. mappings
2. hashes
3. associative arrays
4. all of these
Answer
all of these
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
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(d.items())
Output
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.setdefault("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:
Output
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
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:
Output
2. pop() method removes the item with the specified key name: For example:
Output
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
Output
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()
d = {}
d.popitem()
Output
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
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
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
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
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
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 17
d1 = {"abc":5,"def":6,"ghi":7}
print(d1[0])
1. abc
2. 5
3. {"abc":5}
4. Error
Answer
Error
Reason — In Dictionaries, the elements are accessed through the keys defined in key:value pairs not by indexes, therefore the
expression d1[0] will raise an error as "0" is no such key defined in d1.
Question 18
Answer
Reason — The update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.
Here {"Che":72, "Bio":80} represents another dictionary with the help of which original d is updated i.e. the value of keys: "Che" and
"Bio" are updated to 72 and 80 respectively.
Question 19
1. {"Jo":1,"Ra":2,"Ph":2}
2. {"Jo":1,"Ra":2}
3. {"Jo":1,"Ph":2}
4. Error
Answer
Reason — The update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.
Here, {"Phoebe":2} is a dictionary of key named "Phoebe" which is not present in dict. Therefore, update function will add this key and its
corresponding value to original dictionary dict.
Note: There is a misprint in the options provided in the book.
Question 20
Which of the following will delete key_value pair for key="tiger" in dictionary?
1. del di["tiger"]
2. di["tiger"].delete( )
3. delete(di["tiger"])
4. del(di.["tiger"])
Answer
del di["tiger"]
Reason — del keyword is used to delete an item with the specified key name. Here, tiger is the key name which is specified with del statement
in expression: del di["tiger"]. Hence, it will delete tiger entry from the di.
Question 21
1. print(len(d1))
2. print(d1.get("b"))
3. d1["a"] = 5
4. None of these
Answer
None of these
Question 22
Which of the following Python codes will give the same output if
Answer
(i), (ii)
Reason — Expression dict.pop("book") and del dict["book"] will give same output as both of them are removing the key "book" from
dict i.e., {'diary': 1, 'novel': 5}
Question 23
d1 = {"a":10,"b":2,"c":3}
str1=""
for i in d1:
str1 = str1 + str(d1[i]) + " "
str2 = str1[:-1]
print(str2[::-1])
1. 3, 2
2. 3, 2, 10
3. 3, 2, 01
4. Error
Answer
3, 2, 01
Now the expression str2[::-1] will reverse the string "10 2 3" to '3 2 01'
Question 24
Running the code sorted(my_dictionary, reverse = True) on a dictionary named my_dictionary will return results sorted in what order?
Answer
Descending order (Z-A), by key
Reason — The sorted() function returns a sorted list of dictionary keys. By default, the sort order is ascending. To sort the keys in descending
order, the reverse parameter must be set to true as an optional argument (sorted(my_dictionary, reverse = True)).
Question 1
Question 2
Question 3
Question 4
Question 5
Question 6
The del statement will raise an error if the given key is not found in the dictionary.
Question 8
The pop() function allows to specify own value/message, if the given key is not found in the dictionary.
Question 9
The popitem( ) function will always remove the last entered value of a dictionary.
Question 10
For sum() function to work, the keys of a dictionary must be addition compatible.
True/False Questions
Question 1
In Python, a dictionary can have two same keys with different values.
False
Question 2
In Python, a dictionary can have two same values with different keys.
True
Question 3
Dictionaries are unordered set of elements.
True
Question 4
Question 5
In Python, a dictionary can have two same keys or same values but cannot have two same key-value pair.
False
Question 6
In Python, a dictionary can neither have two same keys nor two same values.
False
Question 7
Question 8
Question 9
The value of a dictionary can be accessed with the help of indices.
False
Question 10
A dictionary is immutable.
False
Question 11
The del statement raises error if the given key is not found in the dictionary.
True
Question 12
Question 13
Question 14
Question 15
The copy( ) method of dictionaries creates a shallow copy of a dictionary.
True
Question 16
The fromkeys( ) creates a dictionary with given keys, each having a different value.
False
Question 1
Answer
Dictionary is termed as an unordered collection of object because the printed order of elements is not same as the order in which the elements are
stored.
Question 2
Answer
1. a Python string
2. a number
3. a tuple (containing only immutable entries)
Question 3
Though tuples are immutable type, yet they cannot always be used as keys in a dictionary. What is the condition to use tuples as a key in a
dictionary ?
Answer
The tuple should contain only immutable entries. Only then it can be used as a key in a dictionary.
Question 4
1. dictionary-values ?
2. dictionary-keys ?
Answer
1. Dictionary values can be all the data types of Python including collections and sequences.
2. Dictionary keys must be of immutable types like a string, a number, a tuple (containing only immutable entries).
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(dictionary.keys())
sorted(dictionary.values())
sorted(dictionary)
sorted(dictionary.items())
For example:
Output
Question 6
In no more than one sentence, explain the following Python error and how it could arise:
This type of error occurs when a mutable type like list is used as a key in dictionary — d1 = {[4, 5] : "a"}
Question 7
Can you check for a value inside a dictionary using in operator? How will you check for a value inside a dictionary using in operator ?
Answer
We cannot directly check for a value inside a dictionary using in operator since in operator searches for a key in a dictionary. We can use
values() function along with in operator to check for a value in dictionary as shown below:
Output
True
Question 8
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
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
Question 9
How is del D and del D[<key>] different from one another if D is a dictionary ?
Answer
del D is used to delete the whole dictionary where as del D[<key>] is used to delete only the key:value pair with the given key.
For example:
d = {1: 'a' , 2 : 'b'}
del d[2]
print(d)
del d
print(d)
Output
{1:'a'}
NameError: name 'd' is not defined.
Question 10
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:
d = {1: 'a' , 2 : 'b'}
d.clear()
print(d)
del d
print(d)
Output
{}
NameError: name 'd' is not defined.
Question 11
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:
Output
Question 12
Answer
pop( ) popitem( )
pop( ) removes the item with the specified popitem( ) removes the last inserted item from the
key name. dictionary.
pop( ) popitem( )
With pop( ), we can specify a return value With popitem( ), we cannot specify any such message/return
or a message if the given key is not found value while deleting from an empty dictionary. It will raise
in the dictionary. an error in this case.
Question 13
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:
Output
[1, 2, 3]
Question 14
Answer
No, max( ) and min( ) will not always work for a dictionary. They will only work with dictionaries having homogeneous keys that can be
compared.
Question 15
Can you use sum( ) for calculating the sum of the values of a dictionary ?
Answer
It is not possible to use the sum( ) function to calculate the sum of values in a dictionary, as sum( ) function only works with the keys, and only
when the keys are homogenous and addition compatible.
We can calculate the sum of the values of a dictionary with the help of values( ) and sum( ) functions as shown in the example below:
Output
Question 16
Answer
A shallow copy of a dictionary refers to a copy of the dictionary whereby only a copy of references (the keys) is created and the content (values
of the dictionary) is not copied.
Question 17
What is the use of copy( ) function ?
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:
Output
Question 18
Answer
Output
d1 = {1:[1,2,3] , 2: [3,4,5]}
d2 = d1.copy()
d2[1].append(4)
print(d2)
print(d1)
Output
Question 1
Which of the following will result in an error for a given valid dictionary D?
1. D + 3
2. D * 3
3. D + {3 : "3"}
4. D.update( {3 : "3"})
5. D.update { {"3" : 3}}
6. D.update("3" : 3)
Answer
Question 2
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:
TypeError: unhashable type: 'list'
This error can be fixed by using a tuple as a key instead of list as shown below:
Question 3
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 :
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]}
Question 4
Nesting of dictionary allows you to store a dictionary inside another dictionary. Then why is following code raising error ? What can you do to
correct it ?
Dictionaries can be stored inside another dictionary as values and not as keys. Here, d4 is storing the other dictionaries as keys which is not
allowed because dictionaries are mutable objects. That's why this code is raising error.
It can be corrected by using d1, d2, d3 as values of d4.
The corrected code is shown below:
Why is following code not giving correct output even when 25 is a member of the dictionary?
The code is not giving the desired output because 25 is present in dic1 as a value and not as a key. "val in dic1" only checks val in the keys of
dictionaries.
We can get the desired output by changing val in dic1 to val in dic1.values().
Question 6
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 7
Consider the following code and then answer the questions that follow :
Answer
Question 8
Output
Dictionary contents
5 : number numbernumbernumber
a : string stringstringstring
(1, 2) : tuple tupletupletuple
Explanation
5 number numbernumbernumber
a string stringstringstring
Question 9(a)
d = dict()
d['left'] = '<'
d['right'] = '>'
print('{left} and {right} or {right} and {left}')
Answer
Output
{left} and {right} or {right} and {left}
Explanation
The argument of print function is a string as it is enclosed in single quotes. Hence, it will get printed as is on the screen.
Question 9(b)
d = dict()
d['left'] = '<'
d['right'] = '>'
d['end'] = ' '
print(d['left'] and d['right'] or d['right'] and d['left'])
print(d['left'] and d['right'] or d['right'] and d['left'] and d['end'])
print((d['left'] and d['right'] or d['right'] and d['left']) and d['end'])
print("end")
Answer
Output
>
>
end
Explanation
Question 9(c)
text = "abracadabraaabbccrr"
counts = {}
ct = 0
lst = []
for word in text:
if word not in lst:
lst.append(word)
counts[word] = 0
ct = ct + 1
counts[word] = counts[word] + 1
print(counts)
print(lst)
Answer
Output
Explanation
This python program counts the frequency of each character in a string. Here is a step-by-step explanation of the program:
Output
{2: 3, 3: 3, 5: 2, 1: 2}
{2: 6, 3: 9, 5: 10, 1: 2}
Explanation
This python program counts the frequency of each number in a list and then multiplies each frequency by its corresponding number. Here is a
step-by-step explanation of the program:
Question 10
Create a dictionary 'ODD' of odd numbers between 1 and 10, where the key is the decimal number and the value is the corresponding number in
words.
Perform the following operations on this dictionary :
Answer
>>> ODD = { 1 : 'One', 3 : 'Three', 5 : 'Five', 7 : 'Seven', 9 : 'Nine' }
>>> ODD.keys()
# (1) Display the keys
>>> ODD.values()
# (2) Display the values
>>> ODD.items()
# (3) Display the items
>>> len(ODD)
# (4) Find the length of the dictionary
>>> 7 in ODD
# (5) Check if 7 is present or not
>>> 2 in ODD
# (6) Check if 2 is present or not
>>> ODD[9]
# (7) Retrieve the value corresponding to the key 9
Output
dict_keys([1, 3, 5, 7, 9])
dict_values(['One', 'Three', 'Five', 'Seven', 'Nine'])
dict_items([(1, 'One'), (3, 'Three'), (5, 'Five'), (7, 'Seven'), (9, 'Nine')])
5
True
False
Nine
Question 11(a)
text = "abracadbra"
counts = {}
for word in text :
counts[word] = counts[word] + 1
Answer
Output
KeyError: 'a'
Explanation
The line counts[word] = counts[word] + 1 will cause a KeyError because we are trying to access a key word of an empty dictionary. As
the key is not present in dictionary counts, hence a KeyError is generated.
Question 11(b)
my_dict = {}
my_dict[(1,2,4)] = 8
my_dict[[4,2,1]] = 10
print(my_dict)
Answer
Output
Explanation
The line my_dict[[4,2,1]] = 10 is in error because a list is being used as a key of the dictionary. Lists being mutable data types are not
allowed as keys in a dictionary.
Question 12(a)
fruit = {}
L1 = ['Apple', 'banana', 'apple']
for index in L1 :
if index in fruit:
fruit[index] += 1
else :
fruit[index] = 1
print(len(fruit))
print(fruit)
Answer
Output
3
{'Apple': 1, 'banana': 1, 'apple': 1}
Explanation
This python program counts the frequency of each fruit in a list and outputs the number of unique fruits and their frequency. The program does
not account for the case sensitivity of the fruit names so "Apple" and "apple" are counted as separate fruits. Here is a step-by-step explanation of
the program:
Question 12(b)
arr = {}
arr[1] = 1
arr['1'] = 2
arr[1] += 1
sum = 0
for k in arr:
sum += arr[k]
print(sum)
Answer
Output
4
Explanation
This python program computes the sum of values of items in the dictionary.
The arr dictionary is created and initialized with two key-value pairs, arr[1] = 1 and arr['1'] = 2. After that, the value of arr[1] is
incremented by 1. At this point arr = {1: 2, '1': 2}.
The program iterates through each key k in the arr dictionary and adds the value arr[k] to the sum variable.
The final value of the sum variable is printed to the console.
Question 13(a)
a = {(1,2):1,(2,3):2}
print(a[1,2])
Answer
Output
Explanation
Question 13(b)
Output
Explanation
Question 14
Find the error/output. Consider below given two sets of codes. Which one will produce an error? Also, predict the output produced by the
correct code.
(a)
box = {}
jars = {'Jam' :4}
crates = {}
box['biscuit'] = 1
box['cake'] = 3
crates['box'] = box
crates['jars'] = jars
print(len(crates[box]))
(b)
box = {}
jars = {'Jam' :4}
crates = {}
box['biscuit'] = 1
box['cake'] = 3
crates['box'] = box
crates['jars'] = jars
print(len(crates['box']))
Answer
Explanation
crates['box'] will return the value of key 'box' from dictionary crates i.e, box. box is itself a dictionary containing two key-value pairs
i.e:
{'biscuit': 1, 'cake': 3}
Therefore, the expression len(crates['box']) becomes len(box) which will return the length of box i.e., 2.
Question 15
dct = {}
dct[1] = 1
dct ['1'] = 2
dct[1.0] = 4
sum = 0
for k in dct:
print(k, sum)
sum += dct[k]
print(sum)
Answer
Output
1 0
1 4
6
Explanation
This python program computes the sum of values of items in the dictionary. It also demonstrates that dictionaries in Python can have both
integer and string keys, but the keys must be unique.
The keys 1 and '1' will be treated as two different keys as the former is a number and the latter is a string. But the keys 1 and 1.0 are
considered the same as both represent number 1.
Here is a step-by-step explanation of the program:
1. The dct dictionary is created and initialized with two key-value pairs, dct[1] = 1 and dct['1'] = 2.
2. After that, dct[1.0] = 4 updates the value of key 1 to 4 as the keys 1 and 1.0 are considered the same. At this point, dct = {1: 4,
'1': 2}.
3. Loop through each key k in dct. Below table shows the loop iterations:
k dct[k] sum Iteration
1 4 0+4=4 Iteration 1
k dct[k] sum Iteration
Question 16
Fill in the blanks of the following code so that the values and keys of dictionary d are inverted to create dictionary fd.
1. items
2. value
3. key
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
Question 2
Write a program to count the number of times a character appears in a given string.
Solution
Output
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
Output
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): ")
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)
Output
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:", d.get(p_name, "Product not found"))
ans = input("Do you want to know price of more products? (y/n): ")
Output
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.
(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
}
if m not in days_in_months:
print("Please enter the correct month")
else:
print("There are", days_in_months[m], "days in", m)
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
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
{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+']}
Question 8
Given the dictionary x = {'k1':'v1', 'k2':'v2', 'k3':'v3'}, create a dictionary with the opposite mapping, i.e., write a program to create the dictionary
as :
inverted_x = {'v1': 'k1' , 'v2' :'k2' , 'v3':'k3'}
Solution
Output
Question 9
Given two dictionaries say D1 and D2. Write a program that lists the overlapping keys of the two dictionaries, i.e., if a key of D1 is also a key of
D2, then list it.
Solution
Output
Question 10
Write a program that checks if two same values in a dictionary have different keys. That is, for dictionary D1 = { 'a' : 10, 'b': 20, 'c' : 10}, the
program should print 2 keys have same values and for dictionary D2 = {'a' : 10, 'b' : 20, 'c' : 30} , the program should print No keys have same
values.
Solution
val = tuple(D1.values())
seen = []
flag = True
for i in val:
if i not in seen:
seen.append(i)
count = val.count(i)
if count > 1:
print(count, "keys have same value of", i)
flag = False
if flag:
print("No keys have same values")
Output
Enter a dictionary D1: {'a': 10, 'b': 20, 'c': 10, 'd': 40, 'e': 10, 'f': 20}
D1 = {'a': 10, 'b': 20, 'c': 10, 'd': 40, 'e': 10, 'f': 20}
3 keys have same value of 10
2 keys have same value of 20
Question 11
d1 = {1:11, 2:12}
d2 = {1:11, 2:12, 3:13, 4:15}
Solution
Output
Question 12
A dictionary D1 has values in the form of lists of numbers. Write a program to create a new dictionary D2 having same keys as D1 but values as
the sum of the list elements e.g.,
D1 = {'A' : [1, 2, 3] , 'B' : [4, 5, 6]}
then
D2 is {'A' :6, 'B' : 15}
Solution
D2 = {}
for key in D1:
num = sum(D1[key])
D2[key] = num
print(D2)
Output