Computer CH - 1 Unit - 7 Session - 1
Computer CH - 1 Unit - 7 Session - 1
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
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
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"
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)")
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])
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.
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")
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.
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
() 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.
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
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
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
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
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
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')
:# 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)
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