Professional Documents
Culture Documents
DICTIONARIES
STD-11
INFORMATICS PRACTICES(12 TH EDITION SUMITA ARORA)
I) INTRODUCTION-Pg 221 blue-don’t write
Def Dictionary- They are mutable unordered collections with elements in the form of key: value pairs that
associate keys to values.
They are Python built-in data types .A dictionary is simply another collection in Python, but with a twist.
Instead of having indexes associated with every element they have keys associated with every element.
So Python dictionaries are a collection of key-value pairs.
Eg-
-{ } mark the beginning and end of the dictionary Note-internally dictionaries are indexed(i,e,
-each entry(key:value) consists of a pair separated by a colon arranged) on the basis of keys.
-The key value pairs are separated by comma(,)
Eg d1={}→empty dictionary
d2={‘Jan’:31,’Feb’:28,’March’:31}
rno=[1,2,3,4]
mks=[67.5,45.6,78.4,70.5]
d={ }
d[r]=m
OR
2. WAP to count the number of times a character appears in a given string.
H/W(Type C)
Q3.WAP to convert a number entered by the user into its corresponding number in words. Eg if the input is 876
then the output should be ‘Eight Seven Six’ using a dictionary.
DICTIONARY IS A MAPPING pg 223 last para (don’t copy)
Note-A dictionary operation that takes a key and finds the corresponding value, is called lookup.
Note- Notice that the keys here are given in quotation marks i.e are of string type.
Note- In python dictionaries, the elements(key:value pairs)are un ordered, one cannot access elements as per
specific order.
Note-If you try to access a key that does not exist then u will get an error.
Note- Like lists the keys and values of a dictionary are stored through their references.
Key Value
‘goose’ 3 {‘goose’:3,’cat’:1}
‘cat’ 1
i)TRAVERSING A DICTIONARY-
It means accessing and processing each element. Tool used is loop.
The for loop makes it easy to traverse or loop over the items.
Prog5-
Note- Dictionary
elements are
unordered, the
order of
assignment of keys
may be different
from what you
stored.
ii) ACCESSING KEYS OR VALUES SIMULTANEOUSLY- To see all the keys of the dictionary at one go use d.keys() and values of
the dictionary use d.values().Both the .keys() and .values() returns the keys and the values in the form of a sequence.You can
convert the returned sequence into a list or a tuple.
Prog7-
<d>.keys() Prog8-
<d>.values() Pg226 P-7.3
tuple(d.keys())
(1,2,3)
set(d.keys())
{1,2,3}
Prog9 pg 227 P-7.4- Given a dictionary with rollno as keys and marks as values. Write code to check if anyone has
scored marks as 89.9.
iii) CHARACTERISTICS OF A DICTIONARY-(don’t copy) pg 227 just write the topic name with the point headings
The only similarity between lists and dictionaries are both are mutable.
1. UNORDERED SET-A dictionary is an unordered set of key: value pairs. You cannot tell the order or position of
key:value pairs in a dictionary as there is no index associated.
2. NOT A SEQUENCE-unlike string, list and tuple, a dictionary is not a sequence because it is unordered set of
elements.
Sequences are indexed by a range of ordinal numbers, hence they are ordered but a dictionary is an unordered
collection.
3. INDEXED BY KEYS, NOT NUMBERS-Dictionaries are indexed by keys. In python a key can be any “non-mutable”
type and values can be of any type and types can be mixed within dictionaries.
Eg- This program has keys of different immutable types-
Pg 227
Don’t copy
Taken as a tuple
Eg-
5.MUTABLE-list,dictionaries are also mutable. We can change the value of a certain key in place.(we can change or
add a new key:value pair.
d[“new”]=“a new value”
Syntax- <dictionary>[<key>]=<value>
Prog10-
Making a change in
a value in place
▪We can also add a new key:value pair to a dictionary using simple
assignment statement.
▪But the key being added should be unique else the value in the
old key will get changed.
Prog11→
6. INTERNALLY STORED AS MAPPING-
▪Internally, the key:value pairs of a dictionary are
associated with one another with some internal
function(called hash function).
▪This way of linking is called mapping.
▪Hash function is an internal algorithm to map
and link a key with a stored value.
Keys Stored values
Key1 value3
Key2 value1
Key3 value2
Prog12→pg228 P-7.5
Prog13→pg228 P-7.6
III) WORKING WITH DICTIONARIES-
i) Initializing a
1) MULTIPLE WAYS OF CREATING A DICTIONARY dictionary
2) ADDING ELEMENTS TO A DICTIONARY ii) Adding key:value pairs
to an empty
3) UPDATING EXISTING ELEMENTS IN A DICTIONARY dictionary a)
4) DELETING ELEMENTS FROM A DICTIONARY iii) Creating a dictionary b)
with name and value c)
5) CHECKING FOR EXISTENCE OF A KEY pairs. d)
6) PRETTY PRINTING A DICTIONARY
i) Initializing a dictionary-In this method all the key: value pairs of the dictionary are written collectively separated
by commas and enclosed in { } Prog14-
Eg- d={1:’abc’,2:’def’}
ii) Adding key:value pairs to an empty dictionary- D={ }
2 ways of creating empty dictionary
D=dict()
Then add key: value pairs to this empty dictionary.
d1[2][‘b’]→[4,5,6]
Prog18 pg 232 P- 7.9 don’t copy
A dictionary contains details of two workers with their names as keys and other details in the form of dictionary as
value. Write a program to print the workers’ information in records format.
Don’t copy
Note-pg(232) In dictionaries
the updation and addition of
elements are similar in
syntax. But for addition ,the
key must not exist in the
dictionary and for updation
the key must exist in the
dictionary.
3)UPDATING/MODIFYING EXISTING ELEMENTS IN A DICTIONARY-
Prog19- Make sure that the key must exist in the dictionary otherwise new entry will be added to
the dictionary.
Prog20-pg 233 P-7.10
1.
3.
2.
Egs(don’t copy) 4.
4) DELETING ELEMENTS FROM A DICTIONARY- (pop() and del both give a Key error
if the key mentioned is not found)
1. del dict[key]→deletes the element with the given key, if the key not there then KeyError.
2. del dict→deletes all the elements of the dictionary along with the dictionary itself
3. RT(value) dict.pop(key)→deletes the element with the given key and also returns the value that it deletes.
4. RT(value) print(dict.pop(‘key’, “Not Found msg”))→if the given key exists it ignores the msg and goes ahead
to delete, else displays the msg 3 and 4 not in
*note- if you do not pass any argument to the pop method then python raises an error. syllabus (extra)
DELETING ELEMENTS FROM A DICTIONARY-
For deleting elements we can use the del statement/command
1.Syntax- del<dictionary>[<key>]
Prog21-
Note-the key that u are giving along with del should exist in the dictionary else python raises exception KeyError
2.Syntax del <dictionary>
Will delete the entire dictionary and we will not be able to use the dictionary
Prog 22-
5) CHECKING FOR EXISTENCE OF A KEY-
→Membership operators in and not in work with dictionaries. But this checks for the existence of keys only.
→To check for values in a dictionary(called reverse look up), you need to write proper code for that.
Syntax <key> in <dictionary>
True/False
<key> not in <dictionary>
Checking for values in a dictionary
Prog23-
Prog24-
You can make out the keys and the values but if the dictionary is too large then there should be a simpler way to
print the dictionary that makes it more readable and presentable.
For this we need to 1) import the json library 2) use the function dumps() of the json module as per
the syntax json.dumps(<dictionary name>,indent=<n>)
json-Java script object notation
Prog 26- dumps-it converts a python structure into a json string
2) Creating a dictionary-dict() function-it takes a mapping or iterable sequence as an arg and returns a dictionary
created from it.
dict(mapping) mapping-dictionary
dict(iterable) iterable- should be in a nested list or tuple.
Prog27 pg236 P-7.12-Create a dictionary where the key ,value pairs(rollno,marks) are available in 3 diff lists as
[1,67.8],[2,75.5],[3,72.5]
Key ,value
You can pass another dictionary to the dict() to create another dictionary
Eg-
True copy
Eg-
(b)The items() Method-To get all the items(key:value) seq of tuples of the dictionary .These are not returned in any
particular order. The list() may or may not be used in
When 2 variables
used along with
Syntax - Seq of (key:value)tuple <dict>.items() the for loop.
d.items() in a for
Sequence of tuples of loop then x is
key:value pairs given the key and
Prog30- y is given the
value from the
first element
Eg- from the seq
returned by
d.items()
As the items() method returns a sequence of (key value) pairs, you can write a loop having 2 variables to access key
value pairs. value
Prog31-
key
c) The keys() method- This method returns all the keys in the dictionary as a sequence of keys(in the form of a
list).Note that these are returned in no particular order.
Syntax - ([key,key,key…])<dict>.keys()
Accessing the first element from d.keys()
Prog32-
Prog37-
or emp2
5) DELETING ELEMENTS FROM THE DICTIONARY-clear() and del()
Syntax del <dict> #Delete the entire dictionary
del <dict>[<key>] #Delete a key from the dictionary along with its value
Prog38-
del gives an error if key not found
The clear method-This method removes all the items from the dictionary and the dictionary becomes an empty
dictionary post this method.
Note- The clear() removes all the elements of dictionary
Syntax <dict>.clear() and makes it an empty dictionary while del statement
Prog 39- removes the entire dictionary as an object. After del
statement with a dictionary name, the dictionary object no
more exists, not even empty dictionary.
Some useful methods of a dictionary are- extra
white
sorted(<dict>,reverse=True)
extra
3) min(),max(),sum()-
Pg240
X---------------x(end of lesson)
ASSIGNMENTS
MCQ-
pg(240)
(c)3_2_01
E[D[c]]=c
E[D[‘c’]]=‘c’
E[1]=‘c’
Extra programs
Q1. Wap to create a dictionary with rollno, name and marks of n
students and display the names of the students who have marks
above 75. pg(246 Q18)
d={}
Or→
Q2.WAP to find common key:value pairs from 2 dictionaries and shared keys with different items. Pg246 Q19
Q3. Given 2 dictionaries .Those elements which have common keys, their values should be added in the 3rd
dictionary. The third dictionary is made up of elements of the 2 dictionaries. Look at the output first
d={‘a’:20,’b’:5,’d’:3,’c’:10}
Q4.There are 4 candidates such as ‘a’,’b’,’c’,’d’. Each student of the class has to vote to select the class
representative. The voting data is available in the form of the foll dictionary, which stores which rollnno voted for
whom? Q22 pg 247
v={1:'a',2:'b',3:'c',4:'a',5:'a',6:'b',7:'b',8:'a',9:'c,10:’a’}
WAP to calculate total votes for each of the candidates and declare the winner.
or
for x in set(v.values()):
Q6
This line should be indented
inside the if block
pg249
x----------x
End of lesson
EXTRA PROGRAMS
Q1.Q8(Type C pg 254) Write a program to convert the keys of a dictionary to the values of the 2nd dictionary and the
values of the first dictionary to be the keys of the 2nd dictionary.
Q2. Q11(Type C pg 254) write a program to check if a dictionary is contained in another dictionary.
Eg d1={1:11.2:12}
d2={1:11,2:12,3:13,4:15}
Q3.Q9.pg 254 Type C-Given 2 dictionaries D1 and D2,list the overlapping keys of both the dictionaries, if the key of
D1 is also a key of D2 then list it.
[2,3]
End of lesson