Dictionaries QB
Dictionaries QB
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:
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'}
d.update({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'}
d.setdefault(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'}
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:
dict = {'list': 'mutable', 'tuple': 'immutable', 'dictionary': 'mutable'}
dict.popitem()
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(d.items())
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"}
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:
x = ('list', 'set', 'dictionary')
y = 'mutable'
my_dict = dict.fromkeys(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'}
d.pop("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'}
d.popitem()
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 = {}
d.popitem()
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 17
What will be the result of the following code ?
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
What will the following code do?
d = {"Phy":94, "Che":70, "Bio":82, "Eng":95}
d.update({"Che":72, "Bio":80})
1. It will create new dictionary as dict={"Che":72,"Bio":80} and old d will be deleted.
2. It will throw an error as dictionary cannot he updated.
3. It will simply update the dictionary as dict={"Phy":94, "Che":72, "Bio":80, "Eng":95}.
4. It will not throw any error but it will not do any changes in dict.
Answer
It will simply update the dictionary as:
d = {"Phy":94, "Che":72, "Bio":80, "Eng":95}.
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
What will be the result of the following code?
d = {"Jo":1,"Ra":2}
d.update({"Phoebe":2})
print(dict)
1. {"Jo":1,"Ra":2,"Ph":2}
2. {"Jo":1,"Ra":2}
3. {"Jo":1,"Ph":2}
4. Error
Answer
{'Jo': 1, 'Ra': 2, 'Phoebe': 2}
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?
di = {"lion":"wild","tiger":"wild","cat": "domestic", "dog":"domestic"}
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
Which of the following will give error if d1 is as shown below?
d1 = {"a":1, "b":2, "c":3}
1. print(len(d1))
2. print(d1.get("b"))
3. d1["a"] = 5
4. None of these
Answer
None of these
Reason — print(len(d1)) will print the length of d1 i.e. 3
print(d1.get("b")) will return the value of key "b" i.e. 2
d1["a"] = 5 will update the value of key "a" to 5.
Hence, all the expressions above will execute with no error.
Question 22
Which of the following Python codes will give the same output if
dict = {"diary":1, "book":3, "novel":5}
(i) dict.pop("book")
(ii) del dict["book"]
(iii) dict.update({"diary":1,"novel":5})
1. (i), (ii), (iii)
2. (1), (ii)
3. (i), (iii)
4. (ii), (iii)
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
What will be the output of following Python code?
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
Reason — d1 is a dictionary containing three elements. str1 is initialized to an empty string.
Inside the for loop, the values of dictionary d1 are getting concatenated to str1 as a string.
The statement str2 = str1[:-1] takes a slice of str1 from start to end and assigns to str2. So
effectively, this statement is assigning str1 to str2.
The detailed execution of the for loop is shown in the table below:
i d1[i] str(d1[i]) str1 str2
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.
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 14
Will max( ) and min( ) always work for a dictionary ?
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:
d = {"abc" : 1 ,"def" : 2 , "mno" : 3}
sum(d.values())
Output
6
Question 16
What do you understand by shallow copy of a dictionary ?
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:
original_d = {1:'a', 2:'b'}
new_d = original_d.copy()
print(new_d)
Output
{1: 'a', 2: 'b'}
Here, original_d and new_d are two isolated objects, but their contents still share the same
reference i.e ('a','b')
Question 18
Discuss the working of copy( ) if
(i) the values are of immutable types,
(ii) the values are of mutable types.
Answer
(i) the values are of immutable types
If the values are of immutable types then any changes made in the copy created with copy( )
will not be reflected in the original dictionary.
For example:
d1 = {1:'Neha' , 2: 'Saima' , 3: 'Avnit' , 4: 'Ana'}
d2 = d1.copy()
d2[5] = 'Taru'
print(d2)
print(d1)
Output
{1: 'Neha', 2: 'Saima', 3: 'Avnit', 4: 'Ana', 5: 'Taru'}
{1: 'Neha', 2: 'Saima', 3: 'Avnit', 4: 'Ana'}
(ii) the values are of mutable types
If the values are of mutable types then any changes made in the copy created with copy()
will be reflected in the original dictionary.
For example:
d1 = {1:[1,2,3] , 2: [3,4,5]}
d2 = d1.copy()
d2[1].append(4)
print(d2)
print(d1)
Output
{1: [1, 2, 3, 4], 2: [3, 4, 5]}
{1: [1, 2, 3, 4], 2: [3, 4, 5]}
Type B: Application Based Questions
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
1. D + 3 — This will result in an error as dictionary does not support + operation.
2. D * 3 — This will result in an error as dictionary does not support * operation.
3. D + {3 : "3"} — This will result in an error as dictionary does not support + operation..
4. D.update( {3 : "3"}) — This will execute with no error since valid dictionary is passed
to update( ) method.
5. D.update { {"3" : 3}} — This will result in an error since update( ) method syntax
used here is invalid.
6. D.update("3" : 3) — This will result in an error since update( ) method always takes
dictionary as it arguments which is not passed here. Hence it will lead to an error.
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:
d1 = {"a" : 1, 1 : "a", (1, "a") : "two"}
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 = { (1, 2) : [1, 2], (3, 4) : [3, 4]}
dict2 = { ([1], [2]) : [1,2], ([3], [4]) : [3, 4]}
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]}
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 ?
d1 = {1 : 10, 2 : 20, 3 : 30}
d2 = {1 : 40, 2 : 50, 3 : 60}
d3 = {1 : 70, 2 : 80, 3 : 90}
d4 = {d1 : "a", d2 : "b", d3 : "c"}
Answer
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:
d4 = { "a": d1, "b": d2, "c": d3}
Question 5
Why is following code not giving correct output even when 25 is a member of the
dictionary?
dic1 = {'age': 25, 'name': 'xyz', 'salary': 23450.5}
val = dic1['age']
if val in dic1:
print("This is member of the dictionary")
else :
print("This is not a member of the dictionary")
Answer
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
What is the output produced by the following code :
d1 = {5 : [6, 7, 8], "a" : (1, 2, 3)}
print(d1.keys())
print(d1.values())
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 7
Consider the following code and then answer the questions that follow :
myDict = {'a' : 27, 'b' : 43, 'c' : 25, 'd' : 30}
valA =''
for i in myDict :
if i > valA :
valA = i
valB = myDict[i]
print(valA) #Line1
print(valB) #Line2
print(30 in myDict) #Line3
myLst = list(myDict.items())
myLst.sort() #Line4
print(myLst[-1]) #Line5
1. What output does Line 1 produce ?
2. What output does Line 2 produce ?
3. What output does Line 3 produce ?
4. What output does Line 5 produce ?
5. What is the return value from the list sort( ) function (Line 4) ?
Answer
1. The output of line 1 is : 'd'
2. The output of line 2 is: 30
3. The output of line 3 is: False
Since 30 is present in myDict as a value and not as a key.
4. The output of line 5 is: ('d',30)
myLst is a list which is created by dictionary items i.e myDict.items()
Hence, myLst will store ⇒ [('a', 27), ('b', 43), ('c', 25), ('d', 30)]
myLst.sort() will sort the list in ascending order according to the first element of each
tuple. Since the first elements of the tuples are all strings, Python performs
lexicographical sorting, which means that 'a' comes before 'b' and so on.
myLst[-1] will return last element of list i.e.,('d', 30).
5. The sort function in Line 4 will not return any value.
It will sort myLst in place in ascending order according to the first element of each
tuple. Since the first elements of the tuples are all strings, Python performs
lexicographical sorting, which means that 'a' comes before 'b' and so on. The sorted
myLst will be [('a', 27), ('b', 43), ('c', 25), ('d', 30)]
Question 8
What will be the output produced by following code ?
d1 = { 5 : "number", "a" : "string", (1, 2): "tuple" }
print("Dictionary contents")
for x in d1.keys(): # Iterate on a key list
print (x, ':' , d1[x], end = ' ')
print (d1[x] * 3)
print ( )
Answer
Output
Dictionary contents
5 : number numbernumbernumber
a : string stringstringstring
5 number numbernumbernumber
a string stringstringstring
>>> 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
1 4 0+4=4 Iteration 1
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): ")
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)
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 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
}
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
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
{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
x = { "k1" : "v1" , "k2" : "v2", "k3" : "v3"}
inverted_x = {}
for i in x :
inverted_x[x[i]] = i
print(inverted_x)
Output
{'v1': 'k1', 'v2': 'k2', 'v3': 'k3'}
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
d1 = eval(input("Enter first dictionary: "))
d2 = eval(input("Enter second dictionary: "))
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
Write a program to check if a dictionary is contained in another dictionary e.g., if
d1 = {1:11, 2:12}
d2 = {1:11, 2:12, 3:13, 4:15}
then d1 is contained in d2.
Solution
d1 = eval(input("Enter a dictionary d1: "))
d2 = eval(input("Enter a dictionary d2: "))
D2 = {}
for key in D1:
num = sum(D1[key])
D2[key] = num
print(D2)
Output
Enter a dictionary D1: {'A' : [1, 2, 3] , 'B' : [4, 5, 6]}
D1 = {'A': [1, 2, 3], 'B': [4, 5, 6]}
{'A': 6, 'B': 15}