0% found this document useful (0 votes)
25 views20 pages

Computer CH - 1 Unit - 7 Session - 1

Uploaded by

namrata.seal111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views20 pages

Computer CH - 1 Unit - 7 Session - 1

Uploaded by

namrata.seal111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Dictionaries

Introduction 7.1 Introduction


Dictionary You must have realized that Python offers many differernt
Key:Value Pairs
Ways to organize collections (i.e., a bunch of values in a
Working with Dictionaries
single "variable") of data items, such as strings, lists,
4DictionaryFunctions dictionaries, tuples etc. Of these you have already worked
andMethods
with strings, lists and tuples in previous chapters. Now is the
time to work with other collection types. So, in this chapter,
we shall be talking about dictionaries.
In this chapter, you shall be learning about how data-items
are organized in a Python dictionary, how you can access
items from a dictionary, various operations that you can
perform on adictionary and various related functions and
methods.

227
228
7.2
Dictionary - Key:Value Pairs NFORMAICS PRACTIK
Among the built-in Python data types is a very versatile type
called a dictionary. Dictionaries are simply another type of
collection
in Python, but with a twist. Rather than having an DICTIONARIES
Dictionaries
elunordered
ements in
index associated with each data-item (justtlike inlists or strings),
Dictionaries in Python have a"key" and a"value of that key". keys
colecions
key:vtoaluvalues.
e pairs that
That is, Python dictionaries are a collection of some key-value
pairs.
Do not get confused, just read on. Just like in
English
meaning, because for each word, there is a meaning associateddictionaries you Can
with it. In the search for
a won
dictionarieshave some keys (just like English dictionaries have words)
and same
associated. manner, utho
English dictionaries have associated meanings for every
word).
Dictionaries are containers that associate keys to values. This is, in a values (jus lie
you must remember the index value of an way, similar
element from the list, but with the. to lists. In ist,
you'll have toknow the key to find the element in case of
Allthis will become clear to you
7.2.1 Creating a
while you
the dictionaries.
go through following sections. fdictionares,
Dictionary
To create a dictionary, you need to include the key: value
syntax : pairs in curly braces as
per fol owing
<dictionary-name> <key>:<value>, <key>:<value>... }
={
Following is an example dictionary by the name
and the subjects being taught by teachers that stores the names of teachers as kevs
them as values of respective keys.
To see
teachers ={ "Dimple" : "Computer
Dictionary creation
"Harpreet": Science", "Karen": "Sociology",
in action
Notice that "Mathematics", "Sabah" :"Legal Studies" }
) the curly brackets
mark the beginning and end of the
Scan
’ each entry (Key :
Value) consists of a pair separated bydictionary,
a colon - the key and
QR Code corresponding
> the key-value
value is given by writing
colon () between them,
pairs are separated by
As you can see that commas ().
there are four key : value pairs
illustrates the key-value relationships in above
in above
dictionary. Following table
dictionary teachers.
Key-Value pair Key
"Dimple":"Computer Science" Value

"Karen" : "Sociology" "Dimple" "Computer Science"


"Harpreet": "Mathematics" "Karen" "Sociology" NOTE

"Sabah": "Legal Studies" "Harpreet" "Mathematics" Internally, dictionaries


indexed ie,
"Sabah" "Legal Studies" are
arranged) on the basi
of keys.
pICTIONARIES
229
Some more
Consider. dictionary declarations :
dicti= (} #it is an empty dictionary with no
elements
DaysInMonths=={"January" : 31, "February" : 28, "March" : 31, "April":30, "May" : 31,
"June" : 30, "July":31, "August": 31,
"September" : 30,
"October":31, "November":30, "December":31 }
8irdCount ={"Finch": 10, "Myna": 13, "Parakeet" :16,
"Hornbil1" : 15, "Peacock" : 15} NOTE
Dictionaries are also called
Nowyoucaneasilyidentify the keys and corresponding values associative arrays or mappings
from above given dictionaries.
or hashes.

othing that you must know is that keys of a dictionary mustbe of immutable types, such
as

a Python string,
) a number, The keys of a dictionary
o a tuple (containing only immutable entries). must be of immutable types.

livou try to give amutable type as key, Python will give you an error as:"unhashable type' .
see below :
IMPORTANT The above error
>>»> dict3 ={[2,3]:"abc"} TypeError : unhashable type always
means that you have tried to assign a
TypeError: unhashable type: 'list' key with mutable type and Python
dictionaries do not allow this.

7.1 Write a program to read rollnumbers and marks of four students and create a dictionary from it
having rollnumbers as keys.
|ngram

no = Enter Ro11 No., Marks : 1, 67.5


Enter RO11 No., Marks : 2, 45.6
mks =()
Enter Rol] No., Marks:3, 78.4
for a in range (4): Enter ROl1 NO. , Marks: 4, 70.5
r, m= eval(input ("Enter Roll No., Marks :")) Created dictionary
rno.append(r) {1: 67.5, 2: 45.6, 3: 78.4, 4: 70.5}
mks.append (m)
*{mo[e]:mks[e], rno[1] :mks[1], no[2]:mks[2], rno[3]:mks[3] }
print("Created dictionary")
print(d)
Dcionory a Mapping
Dictionaries are actually types of mappings. Amapping type of Python is amutable type that
PS values of one type (the key type) to arbitrary objects (values). In Python, there is currently
One standard mapping type, the dictionary. A dictionary's keys must be of immutable
types.
230

7.2.2 Accessing Elements of a Dictionary


INFORMATICS PRACTICE
key. While in
Whle accessing elements froma dictionary, you need the lists, the
throughelernethnets
accessed
accessed through their index : in dictionaries, the elements are
syntax shown below :
deined n the key:value pairs, as per the
<dictionary-name> [ <key>]
above declared
Inus to access the value for key defined as "Karen" in teachers
will write:
>>> teachers ["Karen"]
and Python will return Sociology
NOTE
dichonary, 9,
A
Similarly, following statement dictionaryoperation that tale
a key and
>>»print ("Karen teaches", teachers ['Karen' }) ponding value,findsis calledthe lookun
will give output as: Karen teaches Sociology

While givingkey inside square brackets gives you access only to the value
mentioned key, mentioning the dictionary name without any square brackets
the entire contents of the dictionary. Consider following example :
corrpriespnondits/ dinsgplathyse
>>»>d=("Vowel1" :"a", vVowel2": "e", "Vowel3" : "1, "Vowel4" : "o", Vowels":"
Displaying the contents of dictionary d; Notice the
Dictionaryd output has shown elements in different order
contains five key : >>> d
value pairs
(Vowel5: 'u, Vowel4 :'o, Vowel3':1,Vowel2 :'e', Vowel1 :'a)
Printing the contents of dictionary d; Notice the
order of elements is different from input order
>>> print (d)
{Vowel5':'u, Vowel4' : 'o, Vowel3' :'i', Vowel2':'e, Vowel1 :'a}
>>> d["Vowel1"]
'a Accessing elements using their Notice that keys given here are
keys ; "Vowel1" and "Vowel4"
are the keys used to access in quotation marks ie, are of
>>> d[Vowel4"] corresponding values. string type.
'o

As per above examples, we can say that key order is not guaranteed in Python. This is because n
Python dictionaries, the elements (key :value pairs) are unordered ; one cannot access element as
per specificorder. Theonly way toaccess a value is through key. Thus we can say that keys a
like indexes to access values from a dictionary.
Also, attempting to access a key that doesn't exist, causes an error. Consider the folow
statement that is trying to access a non-existent key ( 13 ) from dictionary d.
>>» d[13]
Traceback (most recent call last): NOTE
File "<pyshell#7>", line 1, in <module> :
(Keyelements
dKeyError : 13 In Python dictionaries, the elements
access
pairs) are unordered; one cannot
[13] as per specific order.
oter DICTIONARIES 231

The above error means that before we can access the Key Value
walue of a particular key using expression such as "goose" +3
Ir13,we must first ensure the key (13 here) exists in the
"tern"
dictionary.
ike list elements, the keys and values of a dictionary are "hawk"

stored through their references. Figure 7.1 illustrates the


same for a dictionary"goose' lern":3, "hawk":1} Fiqure 7.1 References of keys and values
are stored in a dictionary.

7.2 Consider the dictionary reated in the previous program (program 7.1). Modify the previous program
to check if ihe rollnumber 2 has scored more than 75 marks ?
am Since roll number is the key of the dictionary d[2] will give us the marks of key 2.
# code of program 1
if d[2] >75:
print ("Roll number 2scored", d[2], "(> 75)") Created dictionary
else: {1:67.5, 2: 45.6, 3:78.4, 4: 70.5}
Roll number 2 scored 45.6 (< 75)
print ("Roll number 2 scored", d[2], "(< 75)")

2.2A Traversing a Dictionary


Traversal of a collection means accessing and processing each element of it. Thus traversing a
dictionary also means the same and same is the tool for it,i.e., the Python loops.
The for loop makes it easy to traverse or loop over the items in a dictionary, as per following
syntax :
for <item> in <Dictionary>:
procesS each item here

The loop variable <item> will be assigned the keys of <Dictionary> one by one, (just like, they
are assigned indexes of strings or lists while traversing them), which you can use inside the
body of the for loop.
Consider following example that willillustrate this process. Adictionary namely d1 is defined
with three keys - a number, a string, a tuple of integers.
dl ={ 5: "number",\
"a": "string",\ Recall that to break a statement/expression in multiple
lines,you can use 1' at the end of physical line.
(1,2) : "tuple" }
lo traverse the above dictionary, you can write for loop as :
for key in d1 :
print (key, ":", d1[key] )
he above loop will produce the output as shown below.
a: string
(1, 2): tuple
5: number
232 INFORMATICS PRACTICES -n
How it works
The loop variable key in above loop will be assigned the keys of the Dictionary d1, one at s
time. As dictionary elements are unordered, the order of assignment of keys may be different
from what you stored.
Using the loop variable, which has been assigned one key at atime, the corresponding value is
printed along with the key inside the loop-body using through statement:
it will access value from dictionary d1
print (key, ":", d1[key] ) for given key.

As per above output, loop-variable key will be assigned a' in first iteration and hence the key
"a" and its value "string" will be printed ; in second iteration, key will get element (1, 2) and its
value 'tuple' will be printed along with it ; and so on.
So, you can say that traversing all collections is similar. You can use afor loop to get hold of
indexes or keys and then print or access corresponding values inside the loop-body.
7.3 Write a program to create a phone dictionary for all your friends and print each key value pair in
separate lines.
Irogram PhoneDict ={"Madhav": 1234567, "Steven": 7654321, "Dilpreet" : 6734521,
"Rabiya" : 4563217, "Murughan": 3241567, "Sampree": 4673215 }
for name in PhoneDict :
print (name, ":", PhoneDict[name])

The output produced by above program will be shown below.


Rabiya 4563217 NOTE
Murughan : 3241567
Madhav : 1234567 Dictionaries are unordered set
Dilpreet : 6734521 of elements, the printed order of
elements is not same as the order
Steven : 7654321
you stored the elements in.
Sampree : 4673215

As you can make out from the output, that the loop variable name got assigned the keys
of dictionary PhoneDict, one at a time. For the first iteration, it got the key "Rabiya", tor
the second iteration, it was assigned "Murughan" and so on. Since the dictionaries are
unordered set of elements, the printed order of elements is not same as the order you stored the
elements in.

7.2.2B Accessing Keys or Values Simultaneously


Tosee allthe keys in adictionary in one go, you may write <dictionary>.kevs( ) and to see
all values in one go, you may write <dictionary>.values ), as shown below (for the same
dictionary d created above) :
>>> d.keys()
dict_keys([ Vowel5, Vowel4', Vowel3, "Vowel12', Vowel11])
>>> d.values ()
dict_values (['u, 'o, 'i, 'e, 'a'])
Chopter 7: DICTIONARIES 233

As you can see that the keys() function returns all the keys defined in a dictionary in the form of
asequence and also the values( ) function returns all the values defined in that dictionary in the
form of a sequence.
Youcan convert the sequence returned by keys( )and values( ) functions by using ist( ) as
shown below :
>>» list(d. keys() )
('Vowel5', 'Vowel4', 'Vowel3', 'Vowel2', 'Vowel1' ]
>>» list (d.values( ))
('u', 'o', 'i', 'e', 'a']
7.4 Given a ditionary Mwhich stores the marks of the students of class with roll numbers as the keys and
marks as the values. Write aprogram to check if anyone has scored marks as 89.9.
Irogram
:# code to create the dictionary M
if 89.9 in M.values():
Created dictionary
print("Yes, someone has scored 89.9") {1: 67.5, 2: 45.6, 3: 78.4, 4: 70.5}
else: No one has scored 89.9
print("No one has scored 89.9")

7.2.3 Characieristics of a Dictionary


Dictionaries like lists are mutable and that is the only similarity they have with lists. Otherwise,
dictionaries are different type of data structures with following characteristics :
1. Unordered Set can be of any type, and types can be mixed
A dictionary is a unordered set of key: value: within one dictionary. Following dictionary
dict1 has keys of different immutable types :
pairs. Its values can contain references to any:
type of object. You cannot tell the order or :
>>> dict1 ={
position of key:value pairs in a dictionary as 0:Value for key ", 1:"Value for key 1",
there is no index associated.
"3": "Value for astring-as-a-key",
2. Not a Sequence (4, 5): "Value for a tuple-as-a-key",
Unlike a string, list and tuple, a dictionary is : "and for fun" :7
not asequence because it is unordered set of: }
elements. The sequences are indexed by a range >>> dict1[e]
of ordinal numbers. Hence, they are ordered, Value for key &
Key of Integer type
but a dictionary is an unordered collection.
3. Indexed by Keys, Not Numbers »>dict1[(4, 5)]
"Value for a tuple-as-a-key
Dictionaries are indexed bykeys. According to:
Python, a key can be "any non-mutable type." >>> dict1[4, 5] Two ways of writing
key of tuple type ;
Since strings and numbers are not mutable,: Value for a tuple-as-a-key'
tuple can be given as
you canuse them as a key in a dictionary. And: key - with or without
parentheses.
ta tuple contains immutable objects such as >>> dicti["3"]
Integers or strings etc., then only it can also be Value for a string-as-a-key'
used as a key. But the values in a dictionary :
234
INFORMATICS PRACTICES
>»» dicti ["new"] ="a new pair is
NOTE >» dict1 added"
The keys of a dictionary must be of immutable types {0:Value for key , 1: Value for key
1,
such as numbers or strings. Atuple can also be akey
provided it contains immutable elements.
Value for a tuple-as -a-key, . (4,5):
Adictionary value can be any object, though. Value for a string--as- a-key,'and for
'new :'a new pair is added) furt :1,
4. Keys must be Unique
Each of the keys within a dictionary must be:6. Internally Stored as Mappings
nique. Since keys are used to identify values Internally, the key :value pairs of a
in a dictionary, there cannot be duplicate keys
in a dictionary.
are associated with one another
internal function (called
diwithctionasomery
However, tuo unique keys can have same wayof linking is called mapping. hash-function')..This
values, e.g., consider the same BirdCount
dictionary declared above : 7.5 Write aprogram to create a dictiongry M
which stores the marks of the students of
BirdCount ={"Finch" : 10, "Myna": 13, \ Irogram
class with roll numbers as the keys and
"Parakeet": 16, "Hornbill" : 15,\ marks as the values. Get the number of
"Peacock": 15} students as input.
Tuo uniq1ue keys "Hornbill" and M= ()
"Peacock" having same value.
n=int(input("How many students?"))
Notice that two diferent keys "Hornbill" : for a in range(n):
and "Peacock" have same value 15. r, m= eval(input("Enter Roll No., Marks :"))
5. Dictionaries are Mutable M[r]=m
Like lists, dictionaries are also mutable. We can
print("Created dictionary")
print (M)
change the value ofa certain key "in place"
using the assignment statement as per HOw many students? 5
syntax : Enter Rol1 No., Marks :1, 67.3
<dictionary>[<key>]=<value> Enter Roll No., Marks :2, 54.5
Enter ROl1 No., Marks :3, 77.9
For example, consider the dictionary dict1 Enter Rol1 No., Marks :4, 89.9
defined above : Enter Roll No., Marks :5, 83.5
>>> dict1["3"] Created dictionary
Value for a string-as -a-key' {1: 67.3, 2: 54.5, 3: 77.9, 4: 89.9, 5: 83.5}
>>>dict1["3"] ="Changed to new string"
7.6 Consider dictionary M created in the
>>> dict1["3"]
previous example. Write a program to
Changed to new string Value for key "3" changed rogram modify the marks of a roll number.
using assignment statement Obtain the roll number as inpu.
You can even adda new key:value pair to a : #code for creating dictionary M
dictionary using a simple assignment statement. (same as previous example )
But the key being added should be unigue. If: print("Created dictionary")
the key already exists, then value is simply print (M)
changed as in the assignment statement above. print("To modify marks")
r=int(input("Enter roll number :"))
1 Hash-function is an internal algorithm to map and link a lkey with a stored value.
DICTIONARIES 235
Chapter 7 :

1frinM:
MÍr]= float(input("Enter new marks :")) Created dictionary
{1: 67.3, 2: 54.5, 3: 77.9, 4: 89.9, 5: 83.5}
else: To modify marks
print ("No such roll number found" )
Enter roll number :3
print("ModifiedIdictionary is") Enter new marks :78.0
print(M) Modified dictionary is
{1: 67.3, 2: 54.5, 3: 78.0, 4: 89.9, 5: 83.5}
The output is shown on the right.

3 Working with Dictionaries


After basics of dictionaries, let us discuss about various operations that you can perform on
dictionaries, such as adding elements to dictionaries, updating and deleting elements of
dictionaries. This section is dedicated to the same.
3.1 Multiple Ways of Creating Dictionaries
are
You have learnt to create dictionaries by enclosing key: value pairs in curly braces. There
other ways of creating dictionaries too that we going to discuss here.
To see
. Initializing a Dictionary Multiple dictionary
In this method all the key:value pairs of a dictionary are written creation ways

collectively, separated by commas and enclosed in curly braces.


in action

You have already worked with this method. All the dictionaries
created so far have been created through this method, e.g., following
dictionary Employee is also being created the same way :
Employee ={'name':'John', 'salary : 10000, 'age': 24 } Scan
OR Code

2. Adding ey: value Pairs to an Empty Dictionary


added to it one
In this method, firstly an empty dictionary is created and then keys and values are
pair at a time.
To create an empty dictionary, there are two ways :
below :
() by giving dictionary contents in empty curly braces as shown
Employees = {}
:
(ii) by using dictionary constructor dict( ) as shown below
Employee =dict()
> Next step is to add key :value pairs, one at a time as per syntax given below:
<dictionary> [<key>] = <value>
Employee ['name']='John'
For example, in the adjoining statements we are first adding a Employee ['salary'] =10000
key :value pair of 'name': John' , next statements adds
Enployee['age'] =24
value 10000 for key 'salary' and the third and last statement
adds value 24 for key 'age'.
runtime.
This method of creating dictionaries is used to create dictionaries dynamically, at
3. Creating a Dictionary from name and value Pairs
speci
Using the dict{ ) constructor of dictionary, you can also create a new dictionary initialized from
constructor.
tied set of keys and values. There are multiple ways to provide keys and values to dict( )
236 INFORMATICS PRACTICES X

() Specify Key:Value pairs as keyword arguments to dict( )function, Keysas arguments and
Values as their values. Here the argument names are taken as keys of String type.
kevs are wo
The kes are given as arguments, NOTICE the
enclosed in quotes here : the alues are given after sign.

Employee = dict (name ='John', salary = 10000, age = 24)


See. Pvthon automatically convert argument names
string type keys
>>> Employee
{'salary: 10000, 'age': 24, 'name': 'John' }
() Specify comma-separated key: value pairs. To give key :value pairs in this format, you need
to enclose them in curly braces as shown below :
>>» Employee =dict ({'name':'John', 'salary: 10000, 'age' : 24))
>>> Employee
{'salary: 10000, 'age': 24, 'name' :'John'}
(i) Specify keys separately and corresponding values separately. In this method, the kevs
and values are enclosed separately in parentheses (i.e., as tuples) and are given as arguments to
the zip( ) function, which is then given as argument of dict().
All the kes are given separately enclosed in () and all First group contains all the keys and second
the ialues are given separately enclosed in () as group contains all values in same order as
arguments to zip function. The zip( ) function is given that of corresponding keys.
as argunent of dict( ) constructor
»»Employee = dict(zip( ('name,'salary', 'age'), (John', 10000, 24) ) )
>>> Employee

{'salary : 10000, 'age': 24, 'name' :'John'}


The zip function clubs first value from first set with the first NOTE
value of second set, second value from first set with the second
value of second set, and so on,e.g., in above example, 'name' is Keys are unique within a dic
clubbed with John', 'salary' with 10000 and 'age' with 24. tionary while values may not be.
Using these clubbed values, the dict( ) constructor method
creates key : value pairs for the dictionary.
(iv) Specify Key: Value pairs separately in form of sequences. In this method, one list or tuple
argument is passed to dict(). This argument (passed list or tuple) contains lists/tuples of
individual key: value pairs.
That is,a key: value pair is specified in the form of a list and there are as many lists as
outer list as there are key:value pairs in the dictionary. items of the
Consider the following example: See, there is one list type argument passed to dict( )
constructor.
This list argument, in turn contains all key: value pairs as lists.
(3 list type entries in one list here.)
>>» Employee = dict (L['nane, 'Joh ], ['salary ', 1900], ['age, 24]] )
>>> Employee
{'salary: 10000, 'age' : 24, 'name':'John'}* NOTE

You can also pass a tuple containing tuples or lists The values of a dictionary can be
key : value pairs as elements. containing of any type, but the keys must
be of an immutable data type
such as strings, numbers,or tuples.
Chapter7: DICTIONARIES
237
See following examples : The dict) method is provided tuple argument. The passed tuple
contains list-elements of key, values (3 list entries in one tuple

>>» Empl2 = dict((['name', 'John'], ['salary', 10900],


>>» Empl2
("age', 24] ))
('salary': 10000, 'age': 24, 'name' : 'John' }
NOTE
The dict(0method is provided tuple ar
Rument. The passed tuple contains
tuple-elements of key, values (3 tuple en Important. Using dict() method
>» Empl3 =dict(((name, 'Johrt),(salary, 10000), (age, 24))) to create a dictionary takes
longer time compared to tradi
>>Empl3 tional method of enclosing values
{'salary': 10000, 'age' : 24, 'name':'John'} in (). Thus, it should be avoided
until it becomes a necessity.

7.7 I1rie aprogram to create a dictionary namely Numerals from following two lists.
keys = ["One', 'Two', 'Three']
Ogram values = [1, 2, 3]

keys =["One', 'Two', 'Three' ] Given two lists are : ['one','Two', "Three'] [1, 2. 3]
values = [1, 2, 3] Dictionary created with these 1ists is
{'One': 1, 'Two': 2, 'Three': 3}
Numerals =dict(zip(keys, values) )
Drint( "Given two lists are :", keys , values)
print ("Dictionary created with these lists is")
print (Numerals)
7.3.2 Adding Elements to Dictionary
You can add new elements (key :value pair) to a dictionary using
assigrnment as per
syntax. BUT the key being added must not exist in dictionary and must be unique. following If the key
already exists, then this statement will change the value of existing key and no new entry will be
added to dictionary.
<dictionary> [<key>] =<value> To see
Element addition
Consider the following example: in action

>>» Employee = {'name':'John', 'salary: 10000, 'age': 24}


>>> Employee ['dept] ='Sales' New entry added
>>» Employee
Scan
{'salary: 10000, 'dept':'Sales', 'age': 24, name: John'} QR Code

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.
rogram M=
n= int(input ("Howmany students?"))
for a in range(n):
r, m=eval(input("Enter Roll No., Marks :"))
M[r] =m
238 INFORMATICS PRACTICES -}
HOw many students? 3
print ("Created dictionary") Enter Rol] NO.,
Marks :1,
print (M) Enter Ro1] NO., Marks :2, 67.3
ans = 'y' Enter Rol] NO., Marks
56.4 :3, 88.3
Created dictionary
for ain range(5): (1: 67.3, 2: 88.3, 3: 56,4)
print ("Enter details of new studernt") Enter details of new
r, m= eval(input ("Roll No.,Marks :"))
student
Ro11 N0., Marks :4, 77.2
M[r] =m More students? (y/n) : y
Enter details of new student
print("Dictionary after adding new students") Rol1 NOo., MarkS :5, 88.4
print(M) More students? (y/n):n
Dictionary after adding new
{1: 67.3, 2: 88.3, 3: 56.4,, 4: 77.2,student
5: s
7.3.2A Nesting Dictionaries 38.4.
uses such a
You can even add dictionaries as Values inside a dictionary. P'rogram 7.3
Storing a dictionary inside another dictionary is called nesting of dictionaries. But one thing you
must know about nesting of dictionaries is that, you can store a dictionary as a value only, insid
dictionary.
dictionary. You cannot have a key of dictionary type ; you know the reason - only immutahi
types can form the keys of a dictionary.
7.9 ADictionary contains details of two workers with their names as keys
and other details in the forst
records format.
dictionary as value. Write a program to print the workers' information in
Irogram
Employees ={John : fage : 25, 'salary : 20000}, "Diya : (age :35, 'salary : 50900}}
for key in Employees : Carefully notice, how the elements are being
print ("Employee", key, ": ) accessed from inner dictionaries, stores as values
print ('Age :', str(Employees [key] ['age 1)) Employee John
print ('Salary :', str(Employees[key] [('salary] )) Age : 25
salary: 20000
Employee Diya :
7.3.3 Updating/Modifying Existing Elements in a Dictionary Age : 35
salary: S0000
Updating an element is similar to what we did just now. That is,
you can change value of an existing key using assignment as per
following syntax :
dictionary> [<key>] = <value> NOTE
Consider following example : In Dictionaries, the updation and
>>» Employee ={'name' : John', 'salary: 10000, 'age' : 24) addition of elements are similar
>>» Employee['salary] = 20000 insyntax. But for addition, the
the
>>» Employee key must not exist in
dictionary and for updation, the
{'salary: 20000, 'age': 24, 'name':'John'} dictionary.
key must exist in the
But make sure that the key must exist in the dictionary
otherwise new entry will be added to the dictionary.
Using this technique of adding key:value pairs, you can create dictionaries interactively a
runtime by accepting input from user.
Chopter 7. DICTIONARIES 239

Following program illustrates this.


7.10
Write aprogram to create adictionary containing names of competition winner students as keys and
number of their wins as values.
Irogram
n= int(input ("How many students ? "))
CompWinners ={}
for ain range(n):
key = input ("Nameof the student :")
value =int (input ("Number of competitions won :")
Compwinners [key]=value
HOw many students ? 5
print ("The dictionary now is :") Name of the student : Rohan
Number of competitions Won : 5
print (CompWinners) Name of the student : Zeba
Number of competitions won : 3
The output produced by above code is Name of the student : Nihar
shown on the right: Number of competitions won : 3
Name of the student: Roshan
Number of competitions won : 1
Name off the student : James
Number of competitions won : 5
The dictionary now is :
fNihar : 3,'Rohart : 5, 'zeba: 3, 'Roshar' : 1, 'James : 5}

7.3.4 Deleting Elements from a Dictionary


For deleting elements from a dictionary you can use the del statement as explained below.
Todelete adictionary element or adictionary entry, i.e, akey:value pair, you can use del command.
The syntax for doing so is as given below :
del <dictionary>[ <key>]
Consider the following example :
>>> empl3
{'salary : 10000, 'age': 24, 'name' :'John'}
>>> del empl3 ['age' ]
>>> empl3 See, the dictionary now has
that entry removed
{'salary : 10000, 'name' :'John'}
But with del statement, the key that you are giving to delete must exist in the dictionary,
otherwise Python raises exception (KeyError).
See below:
Trying to delete a non-existent key
>>> del empl3 ['new]

KeyError:'new'
If youjust give the dictionary name along with the del statement without any key, i.e., as:
del <dictionary>
240
INFORMATICS PRACTICES-
then it will delete the whole dictionary and you will nolonger be able to use the
del empl3
>>> empl3
Traceback (most recent call last) :
It will now delete the
dictionary empl3
dictionary.ey.
File "<pyshell#10>", line 1, in <module>
empl3 You can no longer use
the
NameError: name 'empl3' is not defined dictionary empls
dictionary by this name exists now

7.3.5 Checking for Existence of a Key


Usual membership operators in and not in work with dictionaries as well
But they an
check for the existence of keys only. To check for whether a value is present in a
reverse lookup), you need to write proper code for that. (Solved Problem
8 is dihasedctionarony r(ecverallesde
lookup.)
To use a membership operator for a key's presence in a dictionary, you may write statement a
per syntax given below :
<key> in <dictionary>
<key> not in <dictionary>
The in operator will return True if the given key is present in the dictionary, otherwise False
The not in operator willreturn True if the given key is not present in the dicionary,
otherwise False.

Consider the following examples :


>>> empl= {salary: 10000, 'age' : 24, 'name':'John'}
>>» 'age' in empl
True

>>> 'John' in empl


False

>>>'John' not in empl


True John' is not a key, hence Python returned False, as in only
checks in keys of the dictionary.
>>> 'age' not in empl
False
dictionary, it
Please remember that the operators in and not in do not apply on values of a
you use them with dictionary name directly. That is, if you search for something with in ort
operator with a dictionary, it will only look for in the keys of the dictionary and not v
For example,
>>> dict1
('age': 25, 'name': 'xyz', 'salary': 23450.5)
>>>'name' in dict1 NOTE
See, it returned False if you tried to search
True inoperatorches
for a value in a dictionary using in operator Thein andnot onlyinkeysof
>>>'xyz' in dict1 for membership notinvales
False the dictionaryaand
DICTIONARIES 241
Chapter 7 :

However, if you need to search for a value in a dictionary, then you can use the in operator with
<dictionary_name>,values( ), i.e.,
>>>'xyz' in dict1.values()
True Using <dictionary>.values( ), you can look for a value using in operator.

7.11 Consider already created dictionary Mthat stores roll numbers and marks. Write a program to input
a roll number and delete it from the dictionary. Display error message if the roil number does not
rogram exist in the dictionary.
:# dictionary created Created dictionary
print ("Created dictionary") {1: 67.3, 2: 54.5, 3: 77.9, 4: 89.9, 5: 83.5}
Rol1 No. to be deleted? :5
print(M) Rol1 No. 5 deleted from dictionary
rno = int (input ("Roll No. to be deleted ?:")) Final Dictionary
if rno in M
: {1: 67.3, 2: 54.5, 3: 77.9, 4: 89.9}
del M[rno]
print("Roll no.",rno, "deleted from dictionary.")
else:
print ("Roll no.", rno, "does not exist in dictionary.")
print ("FinalDictionary" )
print (M)
7.3.6 Pretty Printing a Dictionary
You generally use print function to print adictionary in Python, e.g, if you have adictionary as
Winners =((Nihar':3, Rohan' :5,'Zeba': 3, Roshan': 1, James': 5land if you give a print( ) to
print it, Python will give result as :
>>> print (Winners) This is default way of printing dictionary in Python

{'Nihar': 3, 'Rohan':5, 'Zeba':3, "Roshan': 1, 'James': 5}


From above style of printing dictionary, you can stillmake out the keys and values, but if the
dictionary is large, then shouldn't there be any way of printing dictionary in away that makes it
more readable and presentable?
Well there certainly is a way. For this, you need to import json module by giving statement
import json (recall that in a program the import statement should be given before using any
function of the imported package).
And then youcan use the function dumps() of json module as per following syntax inside print( ):
json.dumps (<dictionary name>, indernt = <n>)
For exanple, consider following result This n is a number

>>> print(json. dumps(Winners, indent =2))

"Nihar":3, Dictionary name


"Rohan":5,
"Zeba":3,
"Roshan": 1, Key:value pairs in separate lines and 2 spaces in front of every
line because you gave value 2for indent (indent = 2)
"James":5
242

7.4 Dictionary Functions and Methods


INFORMATICS PRACTICES
Let us now talk about various built-in functions and methods provided
manipulate Python dictionaries. by
7.4.1 Get Length of the Dictionary - the len( ) Function Python t
To get the length of the dictionary, ie., the count of the key:value
function. This function returns length of the dictionary, i.e., the count ofpair, you can
elements use the
in the dictionary. The syntax to use this method is given below :
len(<dictionary> )
(key:valueeplaeinlrs )
- Takes dictionary name as argument and returns an integer.
Example :
>>> employee =('name':'John', 'salary:10000, 'age': 24}
>>» len(employee)
3
The len() returns the count of
key: value pairs from the dictionary
>>> employee ['dept]='Sales'
>>>len(employee)
4
See, after adding a new entry, the length of dictionary changed

7.4.2 Creating new Dictionary - the dict() Function


The dict( )function is used to create a new
dictionary from iterables and other dictionaries!
mappings. The syntax to use this function is :
dict (mapping)
dict(iterable)
- Were the dict( ) takes a
mapping or iterable sequence as an argument and
returns a dictionary created from it.
7.12 Create a dictionary where key, value pairs'(
[1, 67.8], [2, 75.5), 3, 72.5] rollno., marks) values are available in 3 different lists as
irogram # store individual lists in a list Created dictionary is
data =[ [ 1, 67.8], [2, 75.5], [3, 72.5]] {1: 67.8, 2: 75.5, 3: 72.5}
d1 =dict (data )
print("Created dictionary is")
print(d1)
rs NOTE
Similarly, you can pass a dictionary to dict( ) to create
another dictionary from it. Passing no argument to Passing no argument to dict{ )will
willcreate an empty dictionary {}. dict( ) create an empty dictionary {}

7.4.3 Accessing Items, Keys and Values - get( ),


You can access individual values, all items, keys and items( ), keys( ), values() Methods
values of the dictionary using the following
<dict>.get() to get value the given key
of method
<dict>. items() to get all the items (the
key:value
<dict>.keys() to get all the keys of the dictionarypairs) of the dictionary
<dict>.values( ) to get all the values of the dictionary
Ogpler7:DICTIONARIES 243

Letuslearn about these methods one by one.


method
get( )
TheWiththis method, you can get the item with the given key, similar to dictionary [ key J. Ifthe key
present, Python by default gives error, but you can specify your own message through
is not
iofault argument as per following syntax :
dictionary>.get( key, [ default ])
Takes key as essential argument and returns corresponding value if the key exists or when key does not
exist, it retums Python's Error if default argument is missing otherwise returns default argument.
Example:
NOTE
>>>empl1
rsalary : 10000, 'dept' :'Sales', 'age': 24, 'name': 'John'} <Dict>.get(<key>) is equivalent to
>>> empl1.get ('dept') <Dict>{<key>].
'Sales'

Goe it returned value for given key if key exists in the dictionary. If youonly speify the key as
argument, which does not exist in the dictionary, then Python will retum error :
>>> empl1.get ('desig')

NameError: name desig' is not defined


In place of error, you can also specify your own custom error message as second argument :
>>> empl1.get('desig, "Not yet")
'Not yet'
>>> empl1.get(desig, "Error!! Key not found")
'Error!! Key not found

2. The items( ) method


This method returns all of the items in the dictionary as a sequence of (key, value) tuples. Note
that these are returned in no particular order.
<dictionary>.items() - Takes no argument ; Returns a sequence of (key, value) pairs
Example : The adjacent code gives output as:
employee= {name': 'John', 'salary : 10000, 'age' : 24} ('salary', 10000)
myList =employee. items () ('age', 24)
for x in myList : ('name ', '3ohn')
print (x)
As the items() function returns a sequence of (key value) pairs, you can write a loop having two
variables to access key value pairs.
For example, The adjacent code gives output as :
empl = {'age': 25, 'name': 'Bhuvan', 'salary': 20090} 25 age
seq=empl.items() Bhuvan name
for ky, vl in seq: 20000 salary
print (val, key)
Inis loop has two iteration variables ky, vl because the function items() returns a list of tuples
nd ky, vl is a tuple assignment that successively iterates through each of the key-value pairs in
die dictionary i.e., each key-value pair is assigned to bop variables ky and vl at a time.
244
3. The keys()
method
You have already worked with this method. This method returns all of
NFORMATICS PRACTIK
as asequence of keys (in form of alist). Note that these are returned in the keys in the d
no
<dictionary>. keys() - Takes no arguinent ; Returns alist
sequence keysparticular
of
Example : >>> employee
('salary : 19000,'dept':'Sales','age' : 24, 'name' :'John')
>>> employee. keys()
('salary, 'dept', 'age', 'name']
4. The volues() method
This method returms all the values from the dictionary as a sequence (a list).
returned in no particular order. The syntax, to use this method is given below : Note hat these
<dictionary> .values() Takes no argument ; Returns a list sequence of values
Example : >>> employee
{'salary : 10000, 'dept':'Sales', 'age':24, 'name': 'John'}
>>> employee.values()
[19000, 'Sales', 24, 'John'}
7.13 The dictionary Sstores the roll
nuwnbers:names of thestudents who have been selected to nomie.
in national event. Write a progra nto display the roll
numbers selected.
rogram

:# dictionary created
print("Created dictionary") Created dictionary
(11: 'siya', 22: 'Ruby', 26:
print (S)
Selected roll numbers are:
'Keith',31: 'Preet', 32:'Hug':
print ("Selected roll numbers are:") dict_keys([11, 22, 26, 31, 32])
print(S.keys ())
7.14 The dictionary Sstores the roll
_umbers:names of the students who have been selected to participcte
in national event. Modify the previous
program to display the names of the selected students.
rogram

: # dictionary created
print("Created dictionary") Created dictionary
print (S) {11: 'siya',22: Ruby', 26: 'Keith',31: 'Preet', 32: 'Hu
print("Selected Students' names ar e:") Selected students' names are:
print( S.values() ) dict_values(['siya', 'Ruby', 'Keith', 'Preet', 'Huma'1)
7.4.4 Extend/Update Dicionary with new key:value Pairs :
update ) Method
The update( ) method merges key :value pairs from the new dictionary into the on
dictionary, adding or replacing as needed. The items in the new dictionary are added to the old
one and override any items alrea dy
there with the same keys.
The syntax to use this method is given
below:
Dictionary to be This dictionary's iterms will be taken
updated for updating other dictionar.
<dictionary>.updat1:(<other-dictionary>)
er 7:DICTIONARIES 245

Example :
>>» employeel ('name' :'John', 'salary: 10000, 'age': 24)
elements of dictionary >>> employee2 ={'name': 'Diya','salary:54000, 'dept':'Sales'}
the
2 have oerridden >> employee1. update(employee2)
ofdictionary
havingthe same keys >>> employee1 new keyvalue pair got udded
Fkos ame' and "salary'
{'salary:54000, 'dept':'Sales', 'name':"Diya', 'age : 24)

Srg ke:value pais updated


>>> employee2 existing keralue pairs upduted
{'salary:54000, dept' :'Sales', 'name': Diya'}
This method is equivalent to the following Python statement :
for key in newDict. keys() :
#newDict is employee2 here
dictionary[k]= newDict[k]
5 Deleting Elements from Dictionary - clear ) and del
To delete a key from adictionary, you have already learnt to use the del statement under
section 7.3.4, which is used as per the syntax :
del <dict> [<key>] #todelete a key from the dictionary <dict>
del <dict> #to delete the whole dictionary <dict>
You can go through section 7.3.4 again to read about the del statement.
clear( ) method
This method removes all items from the dictionary and the dictionary becomes empty dictionary
post this method. The syntax to use this method is given below :
<dictionary>. clear() - Takes no argument, returns no value
Example :
>>> Employee = ('name': 'John', 'salary:10000, 'age' : 24)
>>> Employee.clear()
>>> Employee
{} See, now the dictionary is empty

The clear ) method does not delete the dictionary object, it just deletes all the elements inside the
dictionary and empty dictionary object remains. If, however, you want to delete the dictionary
object itself so that dictionary is also removed and no object remains, thern you can use del
statement along with dictionary name. For example :
NOTE

>»» Employee ={'name':'John, 'salary: 10000, 'age': 24) The clear ) removes all the
>>> del Employee it will delete the complete elements of a dictionary and makes
>>> Employee dictionary it empty dictionary while del
statement removes the complete
See, no 'Employee' object now exists. dictionary as an object. After del
statement with a dictionary name,
that dictionary object no more
NameError : name 'Employee' is not defined exists, not even empty dictionary.
246

Summary of Dictionary Manipulation Functions and Methods INFORMATICS


S.No. Function/ Method [D is Dictionary]
1 len(<D> Returns the number of items inDescription
the
2 <0>.get( key, [ default |) Returns corresponding value if the
Python's Error if default
returns default argument. argument
key
is
dicexitiosntsa,ry.else it
3 <D>,items() Returns asequence of (key,
value) dthenmis ing
4 <D>.keys() Returns a list sequence of keys. pairs, he
5
<D>.values() Returns a list sequence of values.
items
8. <D>.update (<other-dictionary>) Merges key: value pairs from the new
12 <D>.clear()
original dicionary, adding or replacing
Removes all items from the dictionaru. di c needed
as tionary into te
LET US REVISE
Dictionaries are mutable with elements in the form of a key: value pair that
* The keys of a dictionary must be of
associate keys to vaee
immutable types.
Dictionaries are also called associative arrays or mappings or hashes.
* In Python dictionaries, the elements
(key:value pairs) are unordered; one cannot access element as per speciñ nri
Keys of adictionary must be unique.
* Dictionaries can be created in multiple ways - through {} and through dict( )
< In Dictionaries, the updation and constructor.
addition of elements are similar in syntax. But for addition, the key must
the dictionary and for updation, the key must exist in ngt eit:
the dictionary.
To delete an element, you can either use del
statement or clear() method.
* Some useful dictionary methods and functions are : len(),
* The membership operators in and not in only
clear(),get(), items(), keys(), values() and update(
work with dictionary keys.
* The clear() function removes all the items from
*
dictionary but the dictionary object exists as an empty dictionary.
The del <dict> statement removes a dictionary object
along with its items. After this, there exists no dictionary obje.
Other useful functions of dictionary are :
setdefault(), sorted( ), min( ), max( ), sum( ) etc.
bjective Type Questions
OTOs
MULTIPLE CHOICE QUESTIONS
1. Dictionaries are set of elements. 4. Which of the following functions will ret
(a) sorted (b) ordered the key, value pairs of adictionary
(c) unordered (d) random
(a) keys( ) (b) values()
2. Dictionaries are also called (c) items() (d) all of these deke
(2) mappings (b) hashes 5. Which of the following can be used to
(c) associative arrays (d) all of these item(s) from a dictionary?
3. Dictionaries are data types of Python. (a) del statement (b) get( )
(c) getitem( ) (d) all of these errorithe
(a) mutable (b) immutable
an
(c) simple (d) all of these 6. Which of the following will raisedictionary
?
given key is not found in the

You might also like