You are on page 1of 50

LESSON-6

DICTIONARIES
STD-11
INFORMATICS PRACTICES(12 TH EDITION SUMITA ARORA)
I) INTRODUCTION-Pg 221 blue-don’t write

II) DICTIONARY-KEY:VALUE PAIRS

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.

II) i) CREATING A DICTIONARY-

Syntax <dictionary name>={<key>:<value>,<key>:<value>……}

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}

Dictionaries are also called associated arrays or mapping or hashes.


Eg-

If u try to access a key that


does not access then you will
get an error

Unhashable type error cause keys are of mutable


types

v.imp Keys of a dictionary must be of immutable types, such as


- a Python string
-a number
- a tuple (containing only immutable entries)
Prog1-Pg 223 P-7.1

rno=[1,2,3,4]
mks=[67.5,45.6,78.4,70.5]
d={ }

d[r]=m

Before the next slide for h/w


One way to add elements to a dictionary→
refer to pg 245 Q15
H/W(Type C)
1.WAP to enter names of employees and their salaries as input and store them in a dictionary.

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)

II) ii) ACCESSING ELEMENTS OF A DICTIONARY-


i) Traversing a dictionary
You require the key to access the element of
ii) Accessing keys or values
the dictionary.
simultaneously
Prog2-

Display the entire dictionary


Give the key in [ ] it will give you the
corresponding value
Prog3-

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.

Syntax- for <item>in <dictionary>:


process each item here
The loop variable<item> will be assigned the keys of the dictionary one by one(just like , they are assigned indexes
of strings or lists while traversing them. Prog6-pg(225)P-7.2- Wap to ask the user to enter rollno and marks
Prog4- of 4 students and make a dictionary and check if rollno 2 has scored
more than 75 marks?

Same as Prog1-Pg 223


P-7.1

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

4. KEYS MUST BE UNIQUE-


-keys of the dictionary should be unique, they cannot be duplicated. Eg-if u give the same key, no
Same values diff keys error but it will take the
-2 unique keys can have same values latest one and ignore the
previous value

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.

This way of creating a dictionary is used to create dictionaries dynamically at run-time


iii) Creating a dictionary from name value pairs - constructors
Using the dict() constructor u can create a new dictionary initialized from specified set of keys and values.
There are multiple ways to provide the key and value pairs
(a) Specify key:value pairs as keyword arguments to a dict()
*zip() has only 2 arg keys and
Eg- No single quotes cause keys are given as values.
arguments. *zip has its own bracket
*1 seq of zip can be a list and
the other as tuple
* If the length of both the
Like making a True copy of the dictionary seq don’t match then the
non matching items are
(b)Specify key:value pairs-(put an actual dictionary as an arg to dict() constructor) ignored.
Eg
Zip has 1 bracket, inside which there are 2
sequences of keys and values

1st seq 2nd seq


(c) Specify the keys separately and values separately – using the zip()
In this the keys and values are enclosed separately in parentheses and are given as argument to the zip function, which is then given as
argument to the dict().
Eg
Prog15-Program7.7 pg 231(don’t copy) Write a program to create a dictionary namely numerals from the
following two lists-
Eg-
Keys=[‘One’,Two’,’Three’]
Values=[1,2,3]
(d) Specify key and value pairs separately in the form of a sequence-
→One list/tuple is passed to the dict().This arg(list/tuple contains list/tuple of individual key:value pairs.
→The key:value pairs is specified as a list/tuple inside a main list or tuple .
→The main list/tuple should be there. (list/tuple can interchange anywhere)

2)ADDING ELEMENTS TO A DICTIONARY-


Prog16- Adding an element
You can add new elements to a dictionary
using assignment. But the key being added
must no exist in the dictionary and must be Modifying element
unique. If the key already exists, then this
statement will change the value of the existing
Key and no new entry will be added to the
Dictionary.
Prog17-pg231-P-7.8-Write a program to add new students roll numbers and marks in the dictionary M created
with roll numbers as the keys and marks as the values.
NESTED DICTIONARIES-
-Storing a dictionary inside another dictionary is called
Nesting of dictionaries.
-You can store a dictionary as a value only.
You cannot have a key of dictionary type(since it is
Mutable datatype)

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-

Prog25 pg 235 P-7.11 wap to ask a user to enter a rollno and


delete it from the dictionary. Display error msg if the rollno does
not exist in the dictionary

Check for values in a dictionary


6) PRETTY PRINTING A DICTIONARY-
You generally use the print function to print a dictionary in Python.
Eg

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

Key:value pairs in separate lines and 4 spaces in


front of every line because of the indent=4

Notice that even 1 is in “ ”


json requires a print statement
It converts all the keys to a string
form not the values
Json does not allow integer keys!!
IV DICTIONARY FUNCTIONS AND METHODS-
1) len(<dictionary>)-This method returns the number of elements in the dictionary.
Eg

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

Passing no argument to the dict() will create an empty dictionary.


Eg-
same

3) Accessing items, keys and values- get(),items(),keys(),values()


(a) The get() method- This method helps us to get the value from the given key-
Prog 28- Syntax- <dict>.get(key)/<dict>.get(key,[default])-To get value of the given key

Eg-

None value if key not found,


But not an error.
rem-d.get(key)→
no error if key not found
Note- The <dict>.get(<key>) is equivalent to <dict>[<key>].Only in <dict>[key] method if the key is not found it will give an error but with
<dict>.get(key,[default]) we can give a default msg if the given key does not exist.

Prog29- d.get(4)→no error→returns a None


d[4]→error

The x in the for loop with d.items() accesses each element


from the seq of elements returned by d.items()

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

Seq of keys as a list

Same as for x in emp:


print(x)
(d) The values method()-This method returns all the values from the dictionary as a sequence(a list).Note that
these are returned in no particular order.
Syntax ([values,values,values….])<dict>.values()
Prog33- Accessing the 1st element from d.values()

Prog34-Pg 238 P-7.13


Prog 35-Pg 238 P-7.14
4) Extend/Update Dictionary with new key:value Pairs: update() Method-
The update() method merges key:value pairs from the new dictionary into the original dictionary, adding or
replacing as needed. The items in the new dictionary are added to the old one and override any items already there
with the same keys.
Syntax- <old dict>.update(<new dict>)
Prog36-
Old dictionary
New dictionary

This method (update()) is equivalent to the following python statement below-

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

setdefault(), sorted(),min(),max(),sum() etc.


1)setdefault ()-
Prog40-
extra

white

Default is None as value

2) sorted()- Returns a list of sorted keys

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

set will make all the


entries automatically
unique
Q5

Q6
This line should be indented
inside the if block
pg249

Dict.sort() does not exist


V) also
{1.0: 'One', 3.0: 'Three', 5.0: 'Five', 7.0: 'Seven', 9.0:
'Nine'}

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]

Q4.Q12 Type C- d1={‘A’:[1,2,3],’B’:[4,5,6]}


Then d2={‘A’:6,’B’:15} Sum of 4,5,6

End of lesson

You might also like