KK P8 Y0 YFx RU8 ZXR BJR Uc

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

30 CBSE Term II Computer Science XI

CHAPTER 03

Dictionary
In this Chapter...
l Creating a Dictionary l Adding Elements to Dictionary

l Properties of Dictionary Keys l Updating Elements in a Dictionary

l Traversing a Dictionary l Deleting Element from a Dictionary

l Accessing Keys l Membership Operators


or Values Separately l Built-in Methods

In Python, dictionary is an unordered collection of data Key : Value Pair Key Value
values that stored the key : value pair instead of single value “Abhi” : “Manager” “Abhi” “Manager”
as an element. Keys of a dictionary must be unique and of “Manish” : “Project Manager” “Manish” “Project Manager”
immutable data types such as strings, tuples etc. Immutable
means they cannot be changed after creation. But in “Aasha” : “Analyst” “Aasha” “Analyst”
dictionary, key-value can be repeated and be of any type. “Deepak” : “Programmer” “Deepak” “Programmer”
A dictionary is used to map or associate things you want to “Ishika” : “Tester” “Ishika” “Tester”
store the keys you need to get them. A dictionary in Python is We can also create empty dictionary.
just like a dictionary in the real world. Each key-value pair in
a dictionary is separated by a colon (:) whereas each key is For example, dic1 = { }
separated by a comma (,). In dictionary, key will be a single Dictionaries are also called mappings or hashes or associative
element and values can be a list or list within a list, numbers arrays.
etc. If you give list as key, then it will give an Error
>>> dic = {[1, 2]: “math”}
Creating a Dictionary Trackback (most recent call last):
To create a dictionary in Python key : value pair is used. File “<pyshell#7>”, line 1, in <module>
Dictionary is listed in curly brackets, inside these curly dic = {[1, 2]: “math”}
brackets, keys and values are declared. TypeError : unhashable type : ‘list’
Syntax dictionary_name = {key1 : value1, key2 : value2, …}
For example, Properties of Dictionary Keys
>>>Employees = {“Abhi” : “Manager”, “Manish” : “Project There are following points while using dictionary keys as
Manager”, “Aasha” : “Analyst”, “Deepak” : “Programmer”, follows
“Ishika” : “Tester”} (i) More than one entry per key is not allowed (no
>>> Employees duplicate key is allowed).
Here is the example of dictionary named Employees in (ii) Dictionaries’ keys are case sensitive, same key name
which Emplyees’ names stored as keys and designation but with the different case are treated as different in
stored as values of respected keys. Python.
Output (iii) The values in the dictionary can be of any type while
{‘Abhi’: ‘Manager’, ‘Manish’ : ‘Project Manager’, the keys must be immutable like numbers, tuples or
‘Aasha’ : ‘Analyst’, ‘Deepak’ : ‘Programmer’, ‘Ishika’ : ‘Tester’} strings.
We can separate these dictionaries as follows
Accessing Elements from a Output
Keys are
Dictionary 1
In Python, to access the elements from a dictionary, keys are 2
used. While in tuple and list, index is used to access the 3
elements. 4
Syntax dictionary_name[key]
(ii) Iterate Through All Values
To access the respective value of key, that key has to given in
square bracket with dictionary name. Again, in above example, the order of subjects are printed
will change every time.
For example,
For example,
>>>Employees [“Deepak”]
>>>print (“Values are”)
‘Programmer’ >>>for i in dic:
>>>Employees [“Ishika”] print(dic [i])
‘Tester’ Output
You can also give this as Values are
Math
>>>print (“Manish works as a”, Employees [‘Manish’])
Manish works as a Project Manager Science
If you give a key that does not exist in dictionary, then it will English
give an error. So, before to access the value first ensure that Music
key is available in dictionary or not.
(iii) Iterate Through All Keys Value Pairs
>>>Employees [“Tushar”]
We can also iterate dictionary through all keys value pairs.
Trackback (most recent call last):
File “<pyshell#11>”, line1, in <module> For example,
>>>print (“Keys :Values”)
Employees [“Tushar”]
>>>for i in dic :
KeyError : ‘Tushar’
print(i, “:”, dic [i])
If you do not give any key with dictionary name, then it will
give whole dictionary with different order. Output
Keys : Values
For example,
1 : Math
>>>dic = {‘1’ : “Math”, ‘2’ : “Science”, ‘3’ : “English”}
2 : Science
>>>dic
3 : English
{‘1’ : ‘Math’, ‘3’ : ‘English’, ‘2’ : ‘Science’}
4 : Music

Traversing a Dictionary Accessing Keys or


Traversing a dictionary means access each and every element
of it. We can traverse a dictionary using for loop. Values Separately
For example, You can access the keys or values separately in dictionary. To
dic = {1 : “Math”, 2 : “Science”, 3 : “English” 4 : “Music”} access the keys from dictionary, use
There are multiple ways to iterate over (traversing) a (dictionary_name). keys () and to access the values of
dictionary in Python as follows respected keys, use (dictionary_name). values ()
For example,
(i) Iterate Through All Keys >>>dic1 = {“A” : “Science”, “B” : “Math”, “C” : “Computer”,
In above example, the order of subject number will change “D” : “English”}
every time because the dictionary does not store keys in a >>>dic1.keys ()
particular order. dict_keys ([‘B’, ‘C’, ‘A’, ‘D’])
>>>print (“Keys are”) >>>dic1.values ()
>>>for i in dic : dict_values ([‘Math’, ‘Computer’, ‘Science’, ‘English’])
print(i) You can also convert these returned keys and values in list
form.
For example, Updating Elements
>>>list (dic1.keys())
[‘B’, ‘C’, ‘A’, ‘D’]
in a Dictionary
>>list (dic1.values ()) You can update elements that are already exist in a
[‘Math’, ‘Computer’, ‘Science’, ‘English’]
dictionary.
Syntax
Nested Dictionary dictionary_name [key] = value
For example,
Nested dictionary means putting a dictionary inside another
dictionary. Nesting is of great use as kind of information we >>>Student = {11 : ‘Ashi’, 12 : ‘Shivam’, 13 : ‘Shrey’, 14 :
can model in programs expanded greatly. ‘Vicky’}
Syntax >>>Student [12] = ‘Nishant’
Nested_dict = {‘dictA’ : {‘key1’ : ‘value1’}, ‘dictB’ : {‘key2’ : >>>Student
‘value2’}} {11 : ‘Ashi’, 12 : ‘Nishant’, 13 : ‘Shrey’, 14 : ‘Vicky’}
Here, the Nested_dict is a nested dictionary with the You entered a key which is not available in a dictionary, then
dictionary dictA and dictB. They are two dictionaries and it will add that key with respective value.
each having own key and value. >>>Student [15] = ‘Kansal’
For example, >>>Student
>>>Student = {112 : {‘Name’ : ‘Surbhi’, ‘Marks’ : 450, ‘Age’ {11 : ‘Ashi’, 12 : ‘Nishant’, 13 : ‘Shrey’, 14 : ‘Vicky’, 15 :
: 16}, 115 : {‘Name’ : ‘Sahil’, ‘Marks’ : 470, ‘Age’ : 16}} ‘Kansal’}
>>>Student
{112 : {‘Marks’ : 450, ‘Age’ : 16, ‘Name’ : ‘Surbhi’}, Deleting Element from a
115 : {‘Marks’ : 470, ‘Age’ : 16, ‘Name’ : ‘Sahil’}}
Dictionary
Adding Elements to Dictionary There are following ways to delete elements from a
dictionary as follows
In Python dictionary, adding of elements extend it with
single pair of values. One value at a time can be added to a (i) Using del Keyword
dictionary by defining value along with the key. This keyword is used to delete the key that is present in the
Syntax dictionary.
dictionary_name [key] = value Syntax
For example, del dictionary_name [key]
>>>Teacher = {‘Neha’ : ‘Hindi’, ‘Akshay’ : ‘Math’, ‘Parul’ : For example,
‘English’} >>>Teacher = {“Name” : “Ashi”, “Subject”: “Math”, “Id” :
>>>Teacher [‘Nisha’] = ‘Computer’ 2546, “Salary”: 25000}
>>>Teacher >>>Teacher
{‘Akshay’ : ‘Math’, ‘Nisha’ : ‘Computer’ , ‘Neha’ : ‘Hindi’, {‘Subject’: ‘Math’, ‘Name’:
‘Parul’ : English’} ‘Ashi’, ‘Salary’ : 25000,
You can also adding elements into an empty dictionary by ‘Id’ : 2456}
dictionary_name [key] = value >>>del Teacher [‘Id’]
>>>dic = { } >>>Teacher
>>>dic {‘Subject’ : ‘Math’, ‘Name’ : ‘Ashi’, ‘Salary’ : 25000}
{} One drawback of this keyword is that if you want to delete
>>>dic [1] = “Delhi” key that is not exist in dictionary, then it will give exception
>>>dic [2] = “Meerut” error.
>>>dic [3] = “Agra” >>>del Teacher [‘Age’]
>>>dic [4] = “Chandigarh” Trackback (most recent call last):
>>>dic File “<pyshell#4>”, line 1, in <module>
{1 : ‘Delhi’, 2 : ‘Meerut’, 3 : ‘Agra’, 4 : del Teacher [‘Age’]
‘Chandigarh’} KeyError : ‘Age’
(ii) Using pop () method Built-in Methods
This method is used to delete key and respective value from Python has some built-in methods that dictionary objects can
dictionary. call. Some of them are describe below
Syntax
dictionary_name.pop (key) (i) len()
For example, This method is used to return the total length of the
dictionary.
>>>Teacher = {‘Name’ : ‘Ashi’, ‘Subject’ : ‘Math’, ‘Id’ :
Syntax
2546, ‘Salary’ : 25000}
len(dictionary_name)
>>>Teacher
For example,
{‘Subject’ : ‘Math’, ‘Name’ : ‘Ashi’, ‘Salary’ : 25000, ‘Id’ :
>>>dic = {1 : ‘This’, 2 : ‘That’, 3 : ‘The’, 4 : ‘World’}
2546}
>>>len (dic)
>>>Teacher.pop (‘Id’) 4
2546 >>>del dic[2]
>>>Teacher >>>len (dic)
{‘Subject’ : ‘Math’, ‘Name’ : ‘Ashi’, ‘Salary’ : 25000} 3
Advantage over using del keyword is that it provides the >>>dic [5] = ‘Hello’
mechanism to print desired value if tried to remove a non >>>dic [6] = ‘Wonder’
existing dictionary pair. >>>len (dic)
>>>Teacher.pop (‘Age’, “Key not found in dictionary”) 5
‘Key not found in dictionary’ >>>dic
{1 : ‘This’, 3 : ‘The’, 4 : ‘World’, 5 : ‘Hello’, 6 : ‘Wonder’}
Membership Operators
in and not in membership operators are used with dictionary. (ii) clear()
These operators check whether a specific key is present in This method is used to remove the elements of the
dictionary or not. If it is present, then it will give True dictionary. It produces an empty dictionary. It will only
otherwise False. delete elements not a dictionary. It does not take any
Syntax parameter and does not return any value.
Key in dictionary_name Syntax
Key not in dictionary_name dictionary_name.clear()
For example, For example,
>>>Employee = {‘Id’:4598, ‘Name’: ‘Shubham’, >>>dic1 = {“Project” : “All In One”, “Days” : 15, “Level” :
‘Dept’:‘Programmer’, ‘Salary’:35000} “High”}
>>>dic1.clear()
>>>Employee
>>>dic1
{‘Id’:4598, ‘Name’:‘Shubham’, ‘Dept’:‘Programmer’,
{}
‘Salary’:35000}
If you want to delete the dictionary with its elements, then
>>>‘Age’ in Employee
del keyword is used.
False
>>>dic1 = {“Project” : “All in One”, “Days” : 15, “Level” :
>>>‘Id’ in Employee “High”}
True >>>del dic1
>>>‘Designation’ not in Employee >>>dic1
True Trackback (most recent call last) :
These operators do not work on values. File “<pyshell#5>”, line1, in <module>
>>>‘Shubham’ in Employee dic1
False NameError : name ‘dic1’ is not defined
If you want to used values with in and not in operators then
use dictionary_name.values() with value’s name. (iii) get()
>>>‘Shubham’ in Employee.values() This method returns the value for the given key, if present in
True the dictionary. It takes maximum of two parameters.
Syntax (vi) values ( )
dictionary_name.get (Key[, value]) This method returns a view object that displays a list of all
Here, Key to be searched in the dictionary value (optional) the values in the dictionary. It does not take any parameters.
value to be returned if the key not found. The default value is Syntax
None.
dictionary_name.values ()
For example,
For example,
>>>Student = {‘Name’ : ‘Shyam’, ‘Roll No’ : 21, ‘Marks’ : 459,
>>>Teacher = {‘Name’ : ‘Akshat’, ‘Subject’ : ‘Science’,
‘Class’ : 12}
‘Salary’ : 28000, ‘Experience’ : 4}
>>>Student
>>>Teacher.values()
{‘Class’ : 12, ‘Roll No’ : 21, ‘Marks’ : 459, ‘Name’ : ‘Shyam’}
dict_values([28000, ‘Science’, ‘4’, ‘Akshat’])
>>>Student.get (‘Name’)
‘Shyam’ (vii) update ( )
>>>Student.get (‘Age’, ‘Not Found’)
This method updates the dictionary with the elements from
‘Not Found’ the another dictionary object or from an iterable of key/value
>>>Student.get (‘Marks’, ‘Not Found’) pairs.
459
Syntax
(iv) items () dictionary_name1.update (dictionary_name2)
This method returns a view object that displays a list of For example,
dictionary’s (key, value) tuple pairs. items() method does not >>>Teacher = {‘Name’ : ‘Akshat’, ‘Subject’ : ‘Science’,
take any parameters. ‘Salary’ : 28000}
Syntax >>>Teacher1 = {‘Name’ : ‘Akansha’, ‘Salary’ : 25000,
dictionary_name.items() ‘Experience’ : 5}
For example, >>>Teacher.update(Teacher1)
>>>Teacher = {‘Name’ : ‘Akshat’, ‘Subject’ : ‘Science’, >>>Teacher
‘Salary’ : 28000, ‘Experience’ : 4} (‘Salary’ : 25000, ‘Subject’, ‘Science’, ‘Experience’ : 5,
>>>Teacher. items () ‘Name’ : Akansha}
dict_items ([(‘Salary’, 28000), (‘Subject’, ‘Science’),
(‘Experience’, 4), (‘Name’, ‘Akshat’)]) (viii) sorted ()
We can also display this using for loop This method returns a sorted sequence of the keys in the
>>>dic = Teacher.items() dictionary.
>>>for i in dic : Syntax
print (i) sorted (dictionary_name)
Output For example,
(‘Salary’, 28000) >>>Teacher = {‘Name’ : ‘Akshat’, ‘Subject’ : ‘Science’,
(‘Subject’, ‘Science’) ‘Salary’ : 28000, ‘Experience’ : 4}
(‘Experience’, 4) >>>sorted(Teacher)
(‘Name’, ‘Akshat’) [‘Experience’, ‘Name’, ‘Salary’, ‘Subject’]
If a dictionary contains both string and integer as keys, then
(v) keys() it will give an error.
This method returns a view object that displays a list of all >>>dic = {‘One’ : ‘This’, 2 : ‘That’, ‘5’ : ‘World’, ‘Five’ :
the keys in the dictionary. It does not take any parameters. ‘Wonders’}
Syntax >>>sorted (dic)
dictionary_name.keys() Trackback (most recent call last):
For example, File “<pyshell#18>”, line 1, in <module>
>>>Teacher = {‘Name’ : ‘Akshat’, ‘Subject’ : ‘Science’, sorted(dic)
‘Salary’ : 28000, ‘Experience’ : 4} TypeError : unorderable types : str () < int ( )
>>>Teacher.keys()
dict_keys([‘Salary’, ‘Subject’, ‘Experience’, ‘Name’]) (ix) fromkeys()
This method creates a new dictionary from the given
sequence of elements with a value provided by the user.
Syntax Syntax
dict.fromkeys(seq, value) dict.setdefault (key[, default_value])
For example, For example,
>>>key = {1, 2, 3, 4, 5} >>>dic = {‘Akshat’ : 26, ‘Riya’: 24, ‘Shrey’:27}
>>>value = dict.fromkeys (key) >>>dic1 = dic.setdefault (‘Riya’)
>>>print (value) >>>print (‘Dictionary : ’, dic)
{1: None, 2 : None, 3 : None, 4 : None, 5 : None} Dictionary : {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27}
>>>value1 = dict.fromkeys (key, ‘Hello’) >>>print (‘Founded key : ’, dic1)
>>>print (value1) Founded key : 24
{1 : ‘Hello’, 2 : ‘Hello’, 3 : ‘Hello’, 4 : ‘Hello’, 5 : ‘Hello’}
>>> dic1 = dic.setdefault (‘Muskan’)
(x) copy() >>> print (‘Dictionary :’, dic)
This method returns a shallow copy of the dictionary. Dictionary : {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27, ‘Muskan’ :
None}
Syntax
dict.copy( ) >>> print (‘Founded key : ’ , dic1)
Founded key : None
Here, copy( ) method does not take any parameters.
For example, (xiii) max ()
dic = {1 : ‘One’, 2 : ‘Two’, 3 : ‘Three’} This method is used to return the maximum key from the
dic1 = dic. copy ( ) dictionary.
print (‘Original dictionary : ’, dic) Syntax
print (‘Copied dictionary : ’, dic1) max(dict)
Output For example,
Original dictionary : {1 : ‘One’, 2 : ‘Two’, 3 : ‘Three’} dic = {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27}
Copied dictionary : {1 : ‘One’, 2 : ‘Two’, 3 : ‘Three’} dic1 = max(dic)
(xi) popitem () print (‘Dictionary : ’, dic)
This method in dictionary helps to achieve similar purpose. print (‘Maximum key : ’, dic1)
It removes the arbitrary key value pair from the dictionary Output
and returns it as a tuple. There is an update for this method Dictionary : {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27}
from Python version 3.7 onwards.
Maximum key : Shrey
Syntax
dict.popitem( ) (xiv) min ()
For example, This method is used to return the minimum key from the
dic = {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27} dictionary.
print (‘Before deletion : ’, dic) Syntax
dic1 = dic.popitem ( ) min(dict)
print (‘Deleted element’, dic1) For example,
print (‘After deletion :’, dic) dic = {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27}
Output dic1 = min(dic)
Before deletion : {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27} print (‘Dictionary :’, dic)
Deleted element : (‘Shrey’, : 27) print (‘Minimum key :’, dic1)
After deletion : {‘Akshat’ : 26, ‘Riya’ : 24} Output
(xii) setdefault () Dictionary : {‘Akshat’ : 26, ‘Riya’ : 24, ‘Shrey’ : 27}
Minimum key : Akshat
This method returns the value of a key (if the key is in
dictionary). If not, it inserts key with a value to the
dictionary.
36 CBSE Term II Computer Science XI

Chapter
Practice
PART 1 5. What will be the output of the following Python
code snippet?
Objective Questions dic1 = { 1 : ‘One’, 2 : ‘Two’, 3 : ‘Three’}
dic1 = {}
print (len(dic1))
l
Multiple Choice Questions (a) 1 (b) 0 (c) 3 (d) 2
Ans. (b) In the second line of code, the dictionary becomes an
1. What will be the output of the following Python empty dictionary. Thus, length = 0.
code snippet?
d1 = {“Neha”:86, “Yash”:92} 6. What is the output of following code?
d2 = {“Neha”:86, “Yash”:88} dic1 ={11, 12, 13}
d1 > d2 for i in dic1 :
(a) True (b) False print (i)
(c) Error (d) None (a) 11 12 13
(b) {11, 12, 13}{11, 12, 13} {11, 12, 13}
Ans. (c) Arithmetic operator ‘>’ cannot be used with dictionaries.
(c) Error
2. What will be the output of the following Python (d) None
code?
Dic1={}
7. What is the output of following code?
>>> dic = {‘A’ : ‘One’, ‘B’ : ‘Two’ , ‘C’ : ‘Three’ }
Dic1[2]=85
>>> dic.keys ( )
Dic1[1]=[22,23,24]
(a) [‘B’, ‘C’, ‘A’] (b) dict_keys [(‘B’, ‘C’, ‘A’)]
print(Dic1[1][1])
(a) [22,23,24] (b) 23 (c) dict_keys ([‘B’, ‘C’, ‘A’]) (d) keys ([‘B’, ‘C’, ‘A’])
(c) 22 (d) Error Ans. (c) keys() returns a view object that displays a list of all the
keys in the dictionary.
Ans. (b) Now, Dic1={2 : 85, 1 : [22, 23, 24]}. Dic1[1][1] refers to
second element having key on position 1, i.e. 23. In given dictionary, A, B, C are keys, while One, Two, Three
are values.
3. What will be the output of the following Python
code? 8. Which one of the following is correct?
(a) In Python, a dictionary can have two same keys with
dic1 = {0: ‘One’, 1: ‘Two’, 2: ‘Three’}
different values.
for x, y in dic1:
(b) In Python, a dictionary can have two same values with
print(x, y) different keys.
(a) 0 1 2 (b) One Two Three (c) In Python, a dictionary can have two same keys or same
(c) 0 One 1 Two 2 Three (d) Error values but cannot have two same key-value pair.
Ans. (d) It will give Error, because objects of type int are not (d) In Python, a dictionary can neither have two same keys
iterable. nor two same values.
4. What will be the output of the following Python Ans. (b) In Python, a dictionary can have two same values with
different keys.
code snippet?
d = {“Neha” : 140, “Paras” : 145} 9. d1={“abc”:5,“def”:6,“ghi”:7}
print(list(d.keys())) print(d1[0])
(a) [“Neha”, “Paras”] What will be the output of above Python code?
(b) [“Neha” : 140, “Paras” : 145] (a) abc (b) 5 (c) {“abc”:5} (d) Error
(c) (“Neha”, “Paras”) Ans. (d) The given code will show an error. Because 0 is not a key
(d) (“Neha” : 140, “Paras” : 145) in given dictionary abc, def and ghi considered as keys to
Ans. (a) The output of the code is a list containing only keys of the given dictionary.
the dictionary d, with the help of d.keys() method.
10. Which of these about a dictionary is false? Ans. (d) Dictionary is listed in curly brackets, inside these curly
(a) The values of a dictionary can be accessed using keys. brackets, keys and values are declared.
(b) The keys of a dictionary can be accessed using values. Syntax dictionary_name = {key1 : value1, key2 :
(c) Dictionaries are not ordered. value2, ...}
(d) Dictionaries are mutable. 18. ……… operators are used with dictionary to check
Ans. (b) The values of a dictionary can be accessed using keys but whether a specific key is present in dictionary or not.
the keys of a dictionary cannot be accessed using values.
(a) Comparison (b) Membership
11. Keys of a dictionary are (c) Logical (d) Access
(a) mutable (b) immutable Ans. (b) in and not in membership operators are used with
(c) Both (a) and (b) (d) None of these dictionary to check whether a specific key is present in
Ans. (b) Keys of a dictionary must be unique and of immutable dictionary or not. If it is present, then it will give True,
data types such as strings, tuples etc. Immutable means otherwise False.
they cannot be changed after creation. But in dictionary, 19. Which of the following dictionary means putting a
key-value can be repeated and be of any type.
dictionary inside another dictionary?
12. Dictionaries are also called (a) Nested (b) Sub (c) Classic (d) Internal
(a) mappings (b) hashes Ans. (a) Nested dictionary means putting a dictionary inside
(c) associative arrays (d) All of these another dictionary. Nesting is of great use as kind of
Ans. (d) Dictionaries are also called mappings, hashes and information we can model in programs expanded greatly.
associative arrays. These are unordered collection of data 20. What will be the output of following code?
values that stored the key : value pair instead of single value
dic = {“Ansh” : 25, “Ritu” : 26}
as an element. Dictionaries are used to map or associate
things you want to store the keys you need to get them. dic [‘Ritu’]
(a) 25 (b) 26
13. …… method is used to delete key and respective (c) Ritu : 26 (d) “Ritu” : 26
value from dictionary. Ans. (b) In Python, to access the element from a dictionary, keys are
(a) del() (b) delete() used. “Ritu” is the key whose value is 26, so output is 26.
(c) pop() (d) remove()
Ans. (c) pop() method removes an element from the dictionary. It l
Case Based MCQs
removes the element which is associated to the specified
key. If specified key is present in the dictionary , it removes 21. Consider the following dictionary :
and returns its value. If the specified key is not present, it dic = {1 : [ 45, 89, 65], ‘A’ : (23, 45, 6)}
throws an error KeyError. Based on the above code, answer the following
14. Which function returns the value for the given key, questions.
if present in the dictionary? (i) Find the output.
(a) items() (b) get() print (dic.keys())
(c) clear() (d) keys() (a) dict_keys ([‘A’, 1]) (b) dict_key (‘A’, 1)
Ans. (b) get() method returns the value for the given key, if (c) dict_keys (‘A’, 1) (d) dict_key [‘A’, 1]
present in the dictionary. It takes maximum of two
(ii) Choose the correct option of given statement.
Syntax dictionary_name.get (key [,value]) print (dic.values())
15. Each key-value pair in a dictionary is separated by (a) ([45, 89, 65], (23, 45,6))
(a) ; (b) : (b) dict_values ([45, 89, 65]), (23, 45, 6))
(c) , (d) < (c) dict_values ([[45, 89, 65], (23, 45, 6)])
Ans. (b) Each key-value pair in a dictionary is separated by colon (d) dict ([[ 45, 89, 65],(23, 45, 6)])
(:) whereas each key is separated by a comma (,).
(iii) Identify the output of len(dic).
16. A dictionary is used to ……… things you want to (a) 2 (b) 6
store the keys you need to get them. (c) 8 (d) None of these
(a) map (b) associate
(c) Both (a) and (b) (d) None of these
(iv) Which output is best suited for given statement?
dic.get (‘A’)
Ans. (b) A dictionary is used to map or associate things you want
to store the keys you need to get them. (a) 23, 45, 6 (b) (23, 45, 6)
(c) [23, 45, 6] (d) Error
17. Which type of brackets are used to create
dictionary? (v) Each key is separated by which symbol?
(a) [ ] (b) ( ) (a) ; (semicolon) (b) : (colon)
(c) < > (d) { } (c) , (comma) (d) @ (At the rate)
Ans. (i) (a) keys() method returns a view object that displays a list Ans. in and not in membership operators are used with
of all the keys in the dictionary. It does not take any dictionary. These operators check whether a specific key is
parameters. present in dictionary or not. If it is present then it will give
(ii) (c) values() method returns a view object that displays a True, otherwise False.
list of all the values in the dictionary. It does not take any Syntax key in dictionary_name
parameters. key not in dictionary_name
(iii) (a) len() method is used to return the total length of the
dictionary. It counts the number of keys present in the 5. Write the short note on
dictionary. (i) sorted( )
(iv) (b) get () method returns the value for the given key, if
present in the dictionary. It takes maximum of two (ii) fromkeys( )
parameters. Ans. (i) sorted() This method returns a sorted sequence of the
(v) (c) Each key value pair in a dictionary is separated by a keys in the dictionary.
colon (:) whereas each key is separated by a comma (,). In (ii) fromkeys () This method creates a new dictionary from
which, key will be a single element and values can be list the given sequence of elements with a value provided by
or list within a list, numbers etc. the user.
6. Find the output of the following code.
my_dict = {‘data1’ : 200, ‘data2’ : 154, ‘data3’:277}
PART 2 print(sum(my_dict.values()))
Subjective Questions Ans. Output
631
l
Short Answer Type Questions 7. Find the output.
dic = {‘data1’ : 200, ‘data2’ : 56, ‘data3’: 47}
1. How can you add following data in empty result = 1
dictionary? for key in dic:
result = result*dic[key]
Keys Values
print(result)
A Agra Ans. Output
B Bengluru 526400
C Chennai
8. Predict the output.
D Delhi
dic = {1 : [45, 89, 65], ‘A’ : (23, 45, 6)}
Ans. dic = {}
print(dic.keys())
dic[‘A’] = ‘Agra’
print(dic.values())
dic[‘B’] = ‘Bengluru’
Ans. Output
dic[‘C’] = ‘Chennai’
dict_keys([‘A’, 1])
dic[‘D’] = ‘Delhi’
dict_values ([[45, 89, 65], (23, 45, 6)])
2. Find the output.
Student = {1 : ‘Aman’, 2 : ‘Bablu’, 3 : ‘Chandan’} 9. Predict the output.
Student [2] = ‘Sahil’ dic = {‘a’ : 1, ‘b’ : 2, ‘c’ : 3, ‘d’ : 4}
print(Student) print(dic)
Student[4] = ‘Aasha’ if ‘a’ in dic :
print (Student) del dic[‘a’]
print(dic)
Ans. Output
Ans. Output
{1 : ‘Aman’, 2 : ‘Sahil’, 3 : ‘Chandan’}
{‘d’ : 4, ‘a’ : 1, ‘c’ : 3, ‘b’ : 2}
{1 : ‘Aman’, 2 : ‘Sahil’, 3 : ‘Chandan’, 4 : ‘Aasha’}
{‘d’ : 4, ‘c’ : 3, ‘b’ : 2}
3. What is the advantage of pop( ) method over a del 10. What is the use of len( ) method in dictionary?
keyword? Ans. len( ) method is used to return the total length of the
Ans. Advantage of pop( ) method over a del keyword is that it dictionary.
provides the mechanism to print desired value if tried to Syntax len(dictionary_name)
remove a non-existing dictionary pair. For example,
Syntax >>>dic = {1 : ‘One’, 2 : ‘Two’,
dictionary_name.pop(key, ‘Text’) 3 : ‘Three’, 4 : ‘Four’}
4. What are in and not in membership operators in >>>len(dic)
dictionary? 4
11. Read the code shown below and pick out the keys. For example,
d = {“Ansh” : 18, “Varsha” : 20} dic = {‘Anu’ : 20, ‘Rahul’ : 25}
Ans. “Ansh” and “Varsha” dic1 = dic.setdefault(‘Anu’)
print (‘Key : ’, dic1)
12. What will be the output?
Output
dic = {“Ansh” : 25, “Ritu” : 26}
Key : 20
print (list (dic.keys())
Ans. [‘Ansh’, ‘Ritu’] 18. When to use tuple or dictionary in Python? Give
13. Define the popitem ( ) method with its syntax. some examples of programming situations
Ans. popitem ( ) method in dictionary helps to achieve similar
mentioning their usefulness. [NCERT]
purpose. It removes the arbitrary key value pair from the Ans. Tuples are used to store the data which is not intended to
dictionary and returns it as a tuple. There is an update for change during the course of execution of the program.
this method from Python version 3.7 only. For example, if the name of months is needed in a program,
Syntax dict.popitem( ) then the same can be stored in the tuple as generally, the
names will either be iterated for a loop or referenced
14. Write the following methods. sometimes during the execution of the program.
(i) max ( ) (ii) min ( ) Dictionary is used to store associative data like student's roll
Ans. (i) max () This method is used to return the maximum key no. and the student's name. Here, the roll no. will act as a key
from the dictionary. to find the corresponding student’s name. The position of the
Syntax max(dict) data does not matter as the data can easily be searched by
(ii) min ( ) This method is used to return the minimum key using the corresponding key.
from the dictionary. 19. Write a Python program to find the highest 2 values
Syntax min (dict) in a dictionary. [NCERT]
15. Give an example to iterate over (traversing) a Ans. dict1={‘One’:65,‘Two’:12,‘Three’:89,‘Four’:65,‘Fi
dictionary through all keys value pair? ve’:56}
Ans. dic = {1 : ‘One’, 2 : ‘Two’, 3 : ‘Three’, 4 :‘Four’} h=0
sh=0
print (“Keys : Values”)
for key in dict1:
for i in dic :
if dict1[key]>h:
print (i, “:”, dic[i])
sh=h
Output
h=dict1[key]
Keys : Values
print(‘highest value’,h)
1 : One print(‘second highest value’,sh)
2 : Two
3 : Three 20. Write a Python program to create a dictionary from
4 : Four a string.
Note: Track the count of the letters from the string.
16. Define clear( ) method in dictionary.
Sample string : ‘w3resource’
Ans. clear( ) method is used to remove the elements of the
dictionary. It produces an empty dictionary. It will only Expected output : {‘3’: 1, ‘s’: 1, ‘r’: 2, ‘u’: 1, ‘w’: 1,
delete elements not a dictionary. It does not take any ‘c’: 1, ‘e’: 2, ‘o’: 1} [NCERT]
parameter and does not return any value. Ans. st = input(“Enter a string: ”)
Syntax dictionary_name.clear() dic = {}
For example, for ch in st:
>>>dic = {1 : ‘One’, 2 : ‘Two’} if ch in dic:
dic[ch] += 1
>>>dic.clear()
else:
>>>dic
dic[ch] = 1
{} for key in dic:
17. Write about the setdefault ( ) method with an print(key,‘:’,dic[key])
example.
Ans. setdefault ( ) method returns the value of a key (if the key is
l
Long Answer Type Questions
in dictionary). If not, it inserts key with a value to the
dictionary.
21. Write a Python program to split dictionary keys and
values into separate lists.
Syntax
Ans. dic = {‘A’ : ‘Apple’, ‘B’ : ‘Ball’, ‘C’ : ‘Cat’, ‘D’ :
dict.setdefault (Key [, default_value])
‘Dog’, ‘E’ : ‘Elephant’}
print(“Original Dictionary:”,str(dic)) for i in a:
# split dictionary into keys and values sum = sum + a[i]
keys = dic.keys() print(sum)
values = dic.values() Ans. (i) 1 (ii) KeyError (iii) 4
#printing keys and values seperately 24. Predict the output.
print (“keys : ”, str(keys))
(i) dic = {}
print (“values : ”, str(values))
dic[1] = 1
Output dic[‘1’] = 2
Original Dictionary : {‘A’ : ‘Apple’, ‘B’ : ‘Ball’, ‘C’ : ‘Cat’, ‘D’ : dic[1.0] = 4
‘Dog’, ‘E’ : ‘Elephant’}
sum = 0
keys : dict_keys ([‘A’, ‘B’, ‘C’, ‘D’, ‘E’]) for i in dic:
values : dict_values ([‘Apple’, ‘Ball’, ‘Cat’, ‘Dog’, ‘Elephant’]) sum = sum + dic[i]
22. Write the short note on following with an example. print(sum)
(i) update( ) (ii) dic = {}
dic [(1, 2, 4)] = 8
(ii) len( ) dic [(4, 2, 1)] = 10
Ans. (i) update( ) This method is used to update the dictionary dic [(1, 2)] = 24
with the elements from the another dictionary object or
sum = 0
from an iterable of key/value pairs.
for i in dic :
Syntax
sum = sum + dic [i]
dictionary_name1.update (dictionary_name2)
print (sum)
e.g.
print (dic)
>>>Student = {1:‘Ashwani’, 2:‘Shiva’, 3:‘Sourabh’,
4:‘Harsh’} Ans. (i) 6
>>>Student [2] = ‘Manish’ (ii) 42
>>>Student {(1, 2) : 24, (4, 2, 1) : 10, (1, 2, 4) : 8}
Output 25. Find the output.
1 : ‘Ashwani’, 2 : ‘Manish’, 3 : ‘Sourabh’, 4 : ‘Harsh’ (i) n = {‘a’ : [2, 3, 1], ‘b’ : [5, 2, 1], ‘c’ : [2, 3,
(ii) len() This method is used to return the total length of the 4]}
dictionary or number of keys. sorted_dic = {i : sorted(j) for i, j in n.items ()}
Syntax print(sorted_dic)
len(dictionary_name) (ii) dict = {‘c’ : 789, ‘a’ : 796, ‘b’ : 908}
e.g. for i in sorted(dict):
dic = {‘A’ : ‘One’, ‘B’ : ‘Two’, ‘C’ : ‘Four’, ‘D’ : print(dict[i])
‘Four’} (iii) students = {‘Sahil’ : {‘Class’ : 11,
dic1 = {‘A’ : ‘One’, ‘B’ : ‘Two, ‘C’ : ‘Three’, ‘D’ : ‘roll_no’ : 21},
‘Four’, ‘E’ : ‘Five’} ‘Puneet’ : {‘Class’ : 11,
dic.update(dic1) ‘roll_no’ : 30}}
print(dic) for i in students :
a = len(dic) print (i)
print(‘The length is’, a) for j in students [i]:
Output print (j, ‘:’, students [i][j])
{‘A’ : ‘One’, ‘B’ : ‘Two’, ‘C’ : ‘Three’, ‘D’ : ‘Four’, ‘E’ : Ans. (i) {‘b’ : [1, 2, 5], ‘c’ : [2, 3, 4], ‘a’ : [1, 2, 3]}
‘Five’} (ii) 796
The length is 5 908
23. Find the output. 789
(iii) Sahil
(i) x = {(1, 2) : 1, (2, 3) : 2}
Class : 11
print (x[1, 2])
roll_no : 21
(ii) x = {‘a’ : 1, ‘b’ : 2, ‘c’ : 3} Puneet
print (x[‘a’, ‘b’]) Class : 11
(iii) a = {} roll_no = 30
a[1] = 1 26. Write a Python program to remove a dictionary
a[‘1’] = 2
from list of dictionaries.
a[1] + = 1
Ans. list1 = [{“id” : 101, “data” : “HappY”},
sum = 0
{“id” : 102, “data” : “BirthDaY”}, print(“Does dictionary contain repetition: ” +
{“id” : 103, “data” : “Vyom”}] str(flag))
print(“The original list is : ”) Output
for a in list1:
The original dictionary : {‘Nikunj’ : 1, ‘Akshat’ : 2, ‘Akansha’ :
print(a)
3, ‘Manish’ : 1}
for i in range(len(list1)):
if list1[i][‘id’] == 103: Does dictionary contain repetition : True
del list1[i] 29. Dictionaries are Python’s implementation of a data
break structure that is more generally known as an
print (“List after deletion of dictionary :”) associative array. A dictionary consists of a
for b in list1: collection of key-value pair. Each key-value pair
print(b)
maps the key to its associated value.
Output
The original list is :
You can define a dictionary by enclosing a
comma-separated list of key-value pair in curly
{‘id’ : 101, ‘data’ : ‘HappY’}
braces {}. A colon (:) separates each key from its
{‘id’ : 102, ‘data’ : ‘BirthDaY’}
associated value:
{‘id’ : 103, ‘data’ : ‘Vyom’}
List after deletion of dictionary : (i) What is dictionary?
{‘id’ : 101, ‘data’ : ‘HappY’} (ii) Is dictionary mutable or immutable?
{‘id’ : 102, ‘data’ : ‘BirthDaY’} (iii) Write the syntax to create dictionary.
27. Find the output of the given Python program. (iv) Can we create empty dictionary?
key1 = [“Data 1”, “Data 2”] (v) Which feature is used to access the elements
name = [“Manish”, “Nitin”] from a dictionary?
marks = [480, 465] Ans. (i) Dictionary is an unordered collection of data values that
print (“The original key list : ” + str(key1)) stored the key : value pair instead of single value as an
print (“The original nested name list : ” + str(name)) element.
print (“The original nested marks list : ” + str(marks)) (ii) Dictionary is immutable which means they cannot be
changed after creation.
output = {key : {‘Name’ : name, ‘Marks’ : marks} for key,
(iii) dictionary_name = {key1 : value1, key2 : value2,
name, marks in zip(key1, name, marks)}
…}
print(“The dictionary after creation :”, str(output))
(iv) Yes, we can create empty dictionary.
Ans. Output For example, dic1 = { }
The original key list : [‘Data 1’, ‘Data 2’] (v) Keys are used to access the elements from a dictionary.
The original nested name list : [‘Manish’, ‘Nitin’]
The original nested marks list : [480, 465]
30. Create a dictionary ‘ODD’ of odd numbers
The dictionary after creation : {‘Data 2’ : {‘Name’ : ‘Nitin’,
between 1 and 10, where the key is the decimal
‘Marks’ : 465}, ‘Data 1’ : {‘Name’ : ‘Manish’, ‘Marks’ : 480}} number and the value is the corresponding number
in words. Perform the following operations on this
28. Write Python program to test if dictionary contains dictionary:
unique keys and values.
(i) Display the keys
Ans. dict1 = {‘Manish’ : 1, ‘Akshat’ : 2, ‘Akansha’ : 3,
‘Nikuj’ : 1} (ii) Display the values
print(“The original dictionary : ” + str(dict1)) (iii) Display the items
flag = False (iv) Length of the dictionary
val = dict() (v) Check if 7 is present or not
for keys in dict1: (vi) Check if 2 is present or not
if dict1[keys] in val: (vii) Retrieve the value corresponding to the key 9
flag = True (viii) Delete the item from the dictionary
break corresponding to the key 9
else : >>> ODD = {1:‘One’,3:‘Three’,5:‘Five’,7:
val[dict1[keys]] = 1 ‘Seven’,9:‘Nine’}
>>> ODD
{1: ‘One’, 3: ‘Three’, 5: ‘Five’, 7: ‘Seven’, 9:
‘Nine’} [NCERT]
Ans. (i) >>> ODD.keys() print(“\n\nEMPLOYEE_NAME\tSALARY”)
dict_keys([1, 3, 5, 7, 9]) for k in employee:
(ii) >>> ODD.values() print(k,‘\t\t’,employee[k])
dict_values([‘One’, ‘Three’, ‘Five’, ‘Seven’, 32. Consider the following dictionary
‘Nine’]) stateCapital = {“AndhraPradesh”:“Hyderabad”,
(iii) >>> ODD.items() “Bihar”:“Patna”,“Maharashtra”:“Mumbai”,
dict_items([(1, ‘One’), (3, ‘Three’), (5, ‘Five’), “Rajasthan”:“Jaipur”}
(7, ‘Seven’), (9, ‘Nine’)])
Find the output of the following statements.
(iv) >>> len(ODD)
5
(i) print(stateCapital.get(“Bihar”))
(v) >>> 7 in ODD (ii) print(stateCapital.keys())
True (iii) print(stateCapital.values())
(vi) >>> 2 in ODD (iv) print(stateCapital.items())
False
(v) print(len(stateCapital))
(vii) >>> ODD.get(9)
‘Nine’
(vi) print(“Maharashtra” in stateCapital)
(viii) >>> del ODD[9] (vii) print(stateCapital.get(“Assam”))
>>> ODD (viii) del stateCapital[“Rajasthan”]
{1: ‘One’, 3: ‘Three’, 5: ‘Five’, 7: ‘Seven’} print(stateCapital) [NCERT]
31. Write a program to enter names of employees and Ans. (i) Patna
their salaries as input and store them in a (ii) dict_keys([‘AndhraPradesh’, ‘Bihar’, ‘Maharashtra’,
dictionary. [NCERT] ‘Rajasthan’])
Ans. num = int(input(“Enter the number of employees: (iii) dict_values([‘Hyderabad’, ‘Patna’, ‘Mumbai’, ‘Jaipur’])
”)) (iv) dict_items([(‘AndhraPradesh’, ‘Hyderabad’), (‘Bihar’,
count = 1 ‘Patna’), (‘Maharashtra’, ‘Mumbai’), (‘Rajasthan’,
employee = dict() ‘Jaipur’)])
while count <= num: (v) 4
name = input(“Enter the name of the (vi) True
Employee: ”) (vii) None
salary = int(input(“Enter the salary: ”)) (viii) {‘AndhraPradesh’: ‘Hyderabad’, ‘Bihar’: ‘Patna’,
employee[name] = salary ‘Maharashtra’: ‘Mumbai’}
count + = 1
Chapter Test
Multiple Choice Questions 8. What is the output of following code?
1. Suppose d = {“Rahul”:40, “Riya”:45}. d={}
a, b, c, = 1, 2, 3
To obtain the number of entries in dictionary which
d[a, b, c] = a + b − c
command do we use?
a, b, c, = 2, 10, 4
(a) d.size() (b) len(d) (c) size(d) (d) d.len()
d[a, b, c] = a + b − c
2. Which of the following is not true about dictionary print (d)
keys?
9. What will be the output of the following Python code
(a) More than one key is not allowed.
snippet?
(b) Keys must be immutable.
(c) Keys must be integers.
dic1 = {1:‘One’, 2:‘Two’, 3:‘Three’}
(d) When duplicate keys encountered, the last assignment del dic1[1]
wins. dic1[1] = ‘Four’
3. What will be the output of the following Python code? del dic1[2]
a={1:5,2:3,3:4} print(len(dic1))
a.pop(3) 10. Write any two properties of dictionary keys.
print(a) 11. Write a program to multiply all the items in a dictionary.
(a) {1: 5}
(b) {1: 5, 2: 3}
12. Write a Python code to iterate over dictionary using for
loop when dictionary is
(c) Error, syntax error for pop() method
(d) {1: 5, 3: 4} dic = {‘A’ : 50, ‘B’ : 100, ‘C’ : 150}

4. What will be the output of the following Python code 13. Write a Python code to concatenate following
snippet? dictionaries to create a new one.
dict1={} d1 = {‘A’ : 10, ‘B’ : 20}
dict1[‘a’]=1 d2 = {‘C’ : 30, ‘D’ : 40}
dict1[‘b’]=[2,3,4] d3 = {‘E’ : 50, ‘F’ : 60}
print(dict1) Long Answer Type Questions
(a) Exception is thrown (b) {‘b’: [2], ‘a’: 1}
(c) {‘b’: [2], ‘a’: [3]} (d) {‘b’: [2, 3, 4], ‘a’: 1} 14. Write Python code which display the nested dictionary.

5. What will be the output of the following Python code?


15. Write Python code to count the frequencies in a list
using dictionary.
>>> dic1={}
>>> dic1.fromkeys([1,2,3],“Hello”) 16. Write Python code to sort the list in a dictionary.
(a) Syntax error (b) {1:”Hello”,2:”Hello”,3:”Hello”} 17. Write Python code to convert dictionary to list of tuple.
(c) “Hello” (d) {1:None,2:None,3:None}
18. Find the output of the given Python code to swap keys
Short Answer Type Questions and values in dictionary.
old_dict = {‘One’ : 742, ‘Two’:145, ‘Three’ : 654,
6. Predict the output.
‘Four’ : 321, ‘Five’ : 120, ‘Six’: 365, ‘Seven’:459,
dic={‘a’ : 1, ‘b’ : 2, ‘c’ : 3, ‘d’ : 4}
‘Eight’: 449}
if ‘a’ in dic :
new_dict = dict([(value, key)for key, value in
del dic[‘a’] old_dict.items()])
print(dic)
print(“Original dictonary is :”)
7. What is the output of following code? print (old_dict)
dic = {} print()
dic[2] = 1 print(“Dictionary after swapping is:”)
dic[‘2’] = 6 print(“Keys:Values”)
dic[2.0] = 8 for i in new_dict:
sum = 0 print(i, “ : ”, new_dict[i])
for i in dic:
sum = sum + dic[i]
print(sum)

Answers
Multiple Choice Questions
1. (b) 2. (c) 3. (b) 4. (d) 5. (b)

You might also like