Chapter - 9 Python Dictionaries
Chapter - 9 Python Dictionaries
PYTHON DICTIONARY
Bimlendu Kumar
PGT Computer Sc.
Kendriya Vidyalaya Garhara
INTRODUCTION
• Dictionary are mutable, unordered collection with elements in
the form of a key:value pairs that associate keys to values.
• Rather than index associated with lists, tuples and strings, a
dictionary has key associated with values.
• It is just like English Dictionary where meaning is associated with
a word (Key).
• Dictionaries are containers that associate keys to values.
• With list, tuples and strings we need to know the index of
individual element to access but with Dictionaries user need to
search value based on key.
CREATING AND ACCESSING LISTS
>>>Month={“January":31,"February":28,"March":31,"April":30,"May
":31,"June":30,"July":31,"August":31,"September":30,"October":31,"
November":30, "December":31}
>>> teacher={'Bimlendu':'9470010804','Prakash':'8604774180'}
Notice that:
1. Curly braces mark the beginning and end of the dictionary
2. Each entry (key:value) consists of a pair separated by a colon. The
key and corresponding value is given by writing colon(:) between
them.
3. The key:value pairs are separated by comma.
Internally dictionaries are indexed (i.e.) arranged on the basis of keys.
SOME MORE DICTIONARY DECLRATION
Emptydisctionary={ }
>>>daynumberofweek={"Monday":1, "Tuesday":2, "Wednesday":3,
"Thursday":4,"Friday":5,"Saturday":6,"Sunday":7}
>>> subjectandcode={"Physics":42,"Chemistry":43,
"Mathematics":41, "Biology":44,"Computer
Science":83,"Informatics Practices":65,"English":101,"Hindi":2}
Note:
• Dictionaries are also called Associative Arrays or mappings or hashes.
• Keys of a dictionaries must be of immutable type such as Python string,
Number, a tuple (containing only immutable entry) but list which is mutable
can not be used as keys of a dictionary.
>>>dict2={[2,3]:”abc”} #TypeError: Un-sharable Type ‘list’
ACCESSING OF A DICTIONARY
Its general syntax is
dictionaryname<“key">
EXAMPLE:
>>> subjectandcode["Hindi"]
2
>>> subjectandcode["Computer Science"]
83
>>> subjectandcode["Informatics Practices"]
65
ACCESSING ENTIRE DICTIONARY
>>>dictionaryname
• Mentioning only the dictionary name without any key prints the
entire dictionary.
• If the key in square bracket is used along with dictionaryname
produces the value that matches the key otherwise error is
displayed.
Example:
>>> subjectandcode
{'Physics': 42, 'Chemistry': 43, 'Mathematics': 41, 'Biology': 44, 'Computer
Science': 83, 'Informatics Practices': 65, 'English': 101, 'Hindi': 2}
>>> subjectandcode["Hindi"]
2
ACCESSING ENTIRE DICTIONARY
• A dictionary operation that takes a key and finds the
corresponding value is called lookup.
• To access a particular value of the dictionary the key is provided in
square bracket is in double quote i.e. of string type.
• In python the elements (key:value pairs) are unordered. It means
one can not access elements as per specific order.
• References of keys and values are stored in dictionaries.
• Dictionaries are unordered set of elements, the printed order of
elements may or may not be in the order in which we have stored
them in the dictionary.
Access Dictionary Keys:Value one by one through Loop
>>> for subject in subjectandcode:
print(subject,":",subjectandcode[subject])
Physics : 42
Chemistry : 43
Mathematics : 41
Biology : 44
Computer Science : 83
Informatics Practices : 65
English : 101
Hindi : 2
Accessing Keys and Values
>>> subjectandcode.keys()
dict_keys(['Physics', 'Chemistry', 'Mathematics', 'Biology', 'Computer
Science', 'Informatics Practices', 'English', 'Hindi'])
>>> subjectandcode.values()
dict_values([42, 43, 41, 44, 83, 65, 101, 2])
>>> subjectandcode["Sanskrit"]=122
>>> subjectandcode
Key 2
value 4
Key 3
value 1
Key 4
value 2
<dictionary>[<key>]=<value>
>>> Subject
{'Computer': '083', 'Informatics Practices': '065', 'English': '101'}
>>> Subject["Enlsih"]="001"
>>> Subject
{'Computer': '083', 'Informatics Practices': '065', 'English': ‘001',}
Note: To add and to update the syntax is exactly same but in case adding the Key must be
a new unique key and for updating the key must be an existing key and the value will be
a new value by which the key value have to be changed.
DELETING ELEMENTS FROM DICTIONARY
We can delete element from a dictionary using following two ways
(a) del <dictionary>[<key>]
(b) <dictionary>.pop(<key>)
>>> Subject
{'Computer': '083', 'Informatics Practices': '065', 'English': ‘001',}
>>> del Subject["English"]
>>> Subject
{'Computer': '083', 'Informatics Practices': '065'}
>>> Subject.pop("Computer")
'083‘ # popped key value is returned by pop() function which is displayed
>>> Subject
{'Informatics Practices': '065', 'English': '001'}
>>> del Subject["IP"]
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
del Subject["IP"]
KeyError: 'IP'
CHECKING FOR EXISTING OF A KEY IN DICTIONARY
Usual Membership operator in and not in work with dictionary as well to
check for the presence / absence of a key in the dictionary.
>>> emp={'age':25,"Salary":10000,"name":"sanjay"}
>>> "age“ in emp
True
>>> "name" in emp
True
>>> "basic" in emp
False
>>> "basic" not in emp
True
But if we want to check whether a value is present in a dictionary (called
reverse lookup) we need to write proper code.
CHECKING FOR VALUE OF EXISTING KEY IN DICTIONARY
The following code can be used to check a value in the dictionary.
dict1={0:"Zero",1:"One",2:"Two",3:"Three",4:"Four",5:"Five"}
ans='y'
while ans=='y' or ans=='Y':
val=input("Enter Vlue: ")
print("Value ",val, end=" ")
for k in dict1:
if dict1[k] == val:
print("Exists at ",k)
break;
else:
print("Not Found")
ans=input("Want to check another value:(y/n)? :- ")
Output
Enter Vlue: Two
Value Two Not Found
Want to check another value:(y/n)? :- y
Enter Vlue: Four
Value Four Exists at 4
Want to check another value:(y/n)? :- n
PRETTY PRINTING A DICTIONARY
>>> Winners={"Nihar":3,"Rohan":5,"Madhu":3,"Roshan":1,"James":5}
>>> print(Winners)
{'Nihar': 3, 'Rohan': 5, 'Madhu': 3, 'Roshan': 1, 'James':
Look the output is not formatted rather it is being displayed in the same manner as it
was being displayed earlier.