KnowledgeBoat Logo
OPEN IN APP

Chapter 13

Dictionaries

Class 11 - Computer Science with Python Sumita Arora



Checkpoint 13.1

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 = dict.fromkeys(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(d.get('a'))
Output
1

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.

  1. 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.

  1. 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

Reasonin 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

Reasonin 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"]

Reasondel 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

Reasonprint(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:

id1[i]str(d1[i])str1str2
"a"10"10""10 ""10"
"b"2"2""10 2 ""10 2"
"c"3"3""10 2 3 ""10 2 3"

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?

  1. Ascending order (A-Z), by key
  2. Ascending order (A-Z), by value
  3. Descending order (Z-A), by key
  4. Descending order (Z-A), by value

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)).

Fill in the Blanks

Question 1

The keys of a dictionary must be of immutable types.

Question 2

The order of a dictionary's elements is undefined or unordered.

Question 3

To delete an element using a key, del statement or pop function is used.

Question 4

To get all the keys of a dictionary, keys() method is used.

Question 5

To create a new dictionary from a set of keys, fromkeys() function is used.

Question 6

The copy( ) method creates a shallow copy of a dictionary.

Question 7

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

A dictionary can have duplicate keys.
False

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

Values of a dictionary can be string, integers or combination of both.
True

Question 8

Keys of a dictionary can be string, integers or combination of both.
True

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

The popitem( ) removes the last entered element from a dictionary.
True

Question 13

The sum( ) can work with all types of dictionaries.
False

Question 14

The sorted( ) function cannot work with dictionaries.
False

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

Type A : Short Answer Questions/Conceptual Questions

Question 1

Why is a dictionary termed as an unordered collection of object?

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

What type of objects can be used as keys in dictionaries ?

Answer

Keys of a dictionary must be of immutable types such as

  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

What all types of values can you store in :

  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:

>>> d = {"def" : 2 ,"abc" : 1, "mno" : 3}
>>> sorted(d.keys())
>>> sorted(d.values())
>>> sorted(d)
>>> sorted(d.items())
Output
['abc', 'def', 'mno']  
[1, 2, 3]  
['abc', 'def', 'mno']  
[('abc', 1), ('def', 2), ('mno', 3)]  

Question 6

In no more than one sentence, explain the following Python error and how it could arise:

TypeError: unhashable type: 'list'

Answer

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:

>>> d = {1: 'a' , 2:'b'}
>>> 'b' in d.values()
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

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

d is a dictionary which contains one key-value pair.
d[2] = 2 adds new key-value pair to d.
d[1] = 3 modifies value of key 1 from 1 to 3.
d[3] = 2 adds new key-value pair to d.
del d[2] deletes the key 2 and its corresponding value.

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

How is clear( ) function different from del <dict> statement ?

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:

d = {1: 'a' , 2 : 'b'} 
d.clear()
print(d)
del d
print(d)
Output
{}
NameError: name 'd' is not defined.

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:

dict.fromkeys(<keys sequence>, [<value>])

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 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 specified key name.popitem( ) removes the last inserted item from the dictionary.
With pop( ), we can specify a return value or a message if the given key is not found in the dictionary.With popitem( ), we cannot specify any such message/return value while deleting from an empty 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

(1, 2) : tuple tupletupletuple
Explanation

d1 is a dictionary containing three key-value pairs.
x in d1.keys() represents that x will iterate on the keys of d1.
The iterations are summarized below:

xd1[x]d1[x] * 3
5numbernumbernumbernumber
astringstringstringstring
(1,2)tupletupletupletuple

Question 9(a)

Predict the output:

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)

Predict the output:

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
  1. print(d['left'] and d['right'] or d['right'] and d['left'])
    1. and operator has higher precedence than or so d['left'] and d['right'] and d['right'] and d['left']) will be evaluated first.
    2. d['left'] and d['right'] will return value of d['right'] i.e. '>' because first operand of and operator is true so it will return the value of second operand.
    3. Similarly, d['right'] and d['left']) will return value of d['left'] i.e. '<'.
    4. Now the expression becomes '>' or '<'. This expression will evaluate to '>' as or operator returns its first operand if the first operand is true. (or operator returns its second operand only when its first operand is false). Thus, '>' gets printed as the first line of the output.
  2. print(d['left'] and d['right'] or d['right'] and d['left'] and d['end'])
    1. and operator has higher precedence than or so d['left'] and d['right'] and d['right'] and d['left'] and d['end'] will be evaluated first.
    2. d['left'] and d['right'] will return value of d['right'] i.e. '>'.
    3. d['right'] and d['left'] will return value of d['left'] i.e. '<'. d['right'] and d['left'] and d['end'] becomes '<' and ' '. and operator returns its second operand in this case so the expression evaluates to ' '.
    4. Now the expression becomes '>' or ' '. or operator will return first operand in this case. Thus, '>' gets printed as the second line of the output.
  3. print((d['left'] and d['right'] or d['right'] and d['left']) and d['end'])
    1. (d['left'] and d['right'] or d['right'] and d['left']) will be evaluated first as it is enclosed in parentheses. From part 1, we know this expression will return '>'.
    2. Now the expression becomes '>' and d['end'] i.e., '>' and ' '. and operator returns ' ', its second argument as its first argument is true. Thus, ' ' gets printed as the third line of the output.

Question 9(c)

Predict the output:

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
{'a': 7, 'b': 4, 'r': 4, 'c': 3, 'd': 1} 
['a', 'b', 'r', 'c', 'd']
Explanation

This python program counts the frequency of each character in a string. Here is a step-by-step explanation of the program:

  1. Initialize the variables
    1. The text variable stores the input string "abracadabraaabbccrr".
    2. The counts variable is a dictionary that stores the frequency of each character in the string.
    3. The ct variable is a counter that keeps track of the total number of characters in the string.
    4. The lst variable is a list that stores the unique characters in the string.
  2. Loop through each character word in the text string
    1. If the character has not been seen before, it is added to the lst list and a new key is added to the counts dictionary with a value of 0.
    2. The ct variable is incremented by 1.
    3. The value of the character's key in the counts dictionary is incremented by 1. This value keeps a count of the number of times this character has appeared in the string so far.
  3. Finally, the counts dictionary and the lst list are printed to the console. The counts dictionary displays the frequency of each character in the string, and the lst list displays the unique characters in the string.

Question 9(d)

Predict the output:

list1 = [2, 3, 3, 2, 5,3, 2, 5, 1,1] 
counts = {}
ct = 0
lst = []
for num in list1:
  if num not in lst:
    lst.append(num)
    counts[num] = 0
  ct = ct+1
  counts[num] = counts[num]+1 
print(counts)
for key in counts.keys():
  counts[key] = key * counts[key] 
print(counts)

Answer

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:

  1. Initialize the variables
    1. The list1 variable stores the input list [2, 3, 3, 2, 5, 3, 2, 5, 1, 1].
    2. The counts variable is a dictionary that stores the frequency of each number in the list.
    3. The ct variable is a counter that keeps track of the total number of numbers in the list.
    4. The lst variable is a list that stores the unique numbers in the list.
  2. Loop through each number num in the list1
    1. If the number has not been seen before, it is added to the lst list and a new key is added to the counts dictionary with a value of 0.
    2. The ct variable is incremented by 1.
    3. The value of the number's key in the counts dictionary is incremented by 1.
  3. The counts dictionary is printed to the console after the first loop, displaying the frequency of each number in the list.
  4. Another loop is executed through the keys in the counts dictionary. For each key, its corresponding value is multiplied by the key and the new value is assigned back to the key in the counts dictionary.
  5. The final counts dictionary is printed to the console, showing the frequency of each number multiplied by the number itself.

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 :

  1. Display the keys
  2. Display the values
  3. Display the items
  4. Find the length of the dictionary
  5. Check if 7 is present or not
  6. Check if 2 is present or not
  7. Retrieve the value corresponding to the key 9
  8. Delete the item from the dictionary corresponding to the key 9

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

>>> del ODD[9]
# (8) Delete the item from the dictionary 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)

Find the errors:

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
TypeError: unhashable type: 'list'
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)

Predict the output:

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:

  1. Initialize the variables
    1. The fruit variable is a dictionary that stores the frequency of each fruit.
    2. The L1 variable stores the input list ['Apple', 'banana', 'apple'].
  2. Loop through each fruit index in the list L1
    1. If the fruit already exists as a key in the fruit dictionary, its value is incremented by 1.
    2. If the fruit is not in the fruit dictionary, a new key is added with a value of 1.
  3. The length of the fruit dictionary is printed to the console, indicating the number of unique fruits.
  4. The fruit dictionary is printed to the console, showing the frequency of each fruit.

Question 12(b)

Predict the output:

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)

Predict the output

a = {(1,2):1,(2,3):2}	
print(a[1,2])

Answer

Output
1
Explanation

a is a dictionary containing two key-value pair.
(1,2) is a key of a. Therefore, a[1,2] represents value of key 1,2 i.e.,1

Question 13(b)

Predict the output

a = {'a':1, 'b':2, 'c':3}
print(a['a','b'])

Answer

Output
KeyError: ('a', 'b')  
Explanation

a is a dictionary containing three key-value pairs.
a['a','b'] will throw an error since given key ('a','b') is not present in dictionary a.

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

The code given in set (a) will produce an error.
In the line print(len(crates[box])), we are trying to print the value from dictionary crates by taking mutable type dictionary i.e box as key — crates[box]. The keys of the dictionary cannot be of mutable type, hence this code produces this error.

The code given in set (b) is correct. Its output is as shown below:

Output of set (b) code
2
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

Predict the output :

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:

kdct[k]sumIteration
140 + 4 = 4Iteration 1
'1'24 + 2 = 6Iteration 2

4. The final value of the sum variable is printed to the console.

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.

d = {'a':1, 'b':2, 'c':3}
print(d)
fd = {}
for key, value in d.____():
  fd[____] = ____ 	
print(fd)

Answer

  1. items
  2. value
  3. key

The completed program is given below for reference:

d = {'a':1, 'b':2, 'c':3}
print(d)
fd = {}
for key, value in d.items():
  fd[value] = key 	
print(fd)

Type C: Programming Practice/Knowledge based Questions

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 = str.count(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 d.values():
    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:", 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
}

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: ['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: "))

print("First dictionary: ", d1)
print("Second dictionary: ", d2)

if len(d1) > len(d2):
    longDict = d1
    shortDict = d2
else:
    longDict = d2
    shortDict = d1

print("overlapping keys in the two dictionaries are:", end=' ')
for i in shortDict:
    if i in longDict:
        print(i, end=' ')
Output
Enter first dictionary: {'a': 1, 'b':2, 'c': 3, 'd': 4}
Enter second dictionary: {'c': 3, 'd': 4, 'e': 5}
First dictionary:  {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Second dictionary:  {'c': 3, 'd': 4, 'e': 5}
overlapping keys in the two dictionaries are: c d

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
D1 = eval(input("Enter a dictionary D1: "))
print("D1 =", D1) 

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

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: "))

print("d1 =", d1) 
print("d2 =", d2)

if len(d1) > len(d2):
    longDict = d1
    shortDict = d2
else:
    longDict = d2
    shortDict = d1
    
for key in shortDict:
      if key in longDict:
            if longDict[key] != shortDict[key]:
                  print("d1 and d2 are different ") 
                  break
      else:
            print("d1 and d2 are different ") 
            break
else:
      print(shortDict, "is contained in", longDict)
Output
Enter a dictionary d1: {1:11, 2:12}  
Enter a dictionary d2: {1:11, 2:12, 3:13, 4:15}
d1 = {1: 11, 2: 12}
d2 = {1: 11, 2: 12, 3: 13, 4: 15}
{1: 11, 2: 12} is contained in {1: 11, 2: 12, 3: 13, 4: 15}

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
D1 = eval(input("Enter a dictionary D1: "))
print("D1 =", D1) 

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}
PrevNext