9.
DICTIONARY
Dictionary is an unordered collection of items where each item is a Key‐Value pair. It is like a
mapping between set of Keys/ Indices and a set of values.
Each key map to a value
Key is separated from value by colon (the items are separated by comma (,)).
Entire dictionary is enclosed within curly bracket { }
Keys are unique while value may not
Dictionary is mutable (Add, Change value of existing items)
Any dictionary have key and value (Key should be unique)
Creating Dictionary
<dictionary name> = {‘key1’ : ‘value1’ , ‘key2’ : ‘value2’ , ‘key3’ : ‘value3’ }
e.g. d={} # empty dictionary
d1 = {‘D’ : ‘Deepawali’, ‘H’: ‘Holi’, ‘R’, ‘Republic Day’}
d2 = {1 : ‘Sunday’ , 2 : ‘Monday’, 3, ‘Tuesday’ }
Method of creating dictionary
1. d1 = { }
type(d1) # <class ‘dict’>
2. d2 = {‘up’, ‘Uttaar Pradesh’, ‘mp’, ‘Madhya Pradesh’ }
3. D = dict();
print(D) #{}
D[1] = ‘one’; #adding items to dictionary
D[2] = ‘two’;
print(D) # {1: ‘one’ , 2 : ‘two’}
Accessing Dictionary elements
Mydict = {‘name’ : ‘cricket’, ‘player’ : 11, gtype : ‘outdoor’}
print(Mydict[‘name’]) # cricket
print(Mydict[‘player’]) # 11
print(Mydict[‘gtype’]) # outdoor
print(Mydict[‘captain’]) # Error
Traversing a dictionary element
Traversing means accessing each element of dictionary
Looping is used for traversing
D5 = {‘p’ : ‘physics’ , ‘c’ : ‘chemistry’ , ‘b’ : ‘biology’, ‘e’ : ‘economics’ }
for i in D5
print(i, ‘:’, D5[i] # 1 : physics
2 : chemistry
3 : biology
4 : economics
Youtube channel : ipcsguide 1 Manish Kumar Gupta
Append a value in dictionary
Add new element to existing dictionary
dyr = {‘Jan’ : ‘January’ , ‘Feb’ : ‘February’}
dyr[‘mar’] = ‘March’;
print(dyr) # {‘Jan’ : ‘January’ , ‘Feb’ : ‘February’ , ‘mar’ : ‘march’}
Update an element in a dictionary
Change / modify any existing element in a dictionary
D6 = {1 : 11, 2 : 22, 3 : 33}
print(D6) # {1 : 11, 2 : 22, 3 : 33}
D6[2] = 2000
print(D6) # {1 : 11, 2 : 2000, 3 : 33}
Dictionary can be merged using “update” function and overwrites the values of the same key
Sub1 = {'p' : 'physics' , 'c' : 'chemistry' , 'b' : 'biology', 'e' : 'economics' }
Sub2 = {'h' : 'hindi' , 'e' : 'english' , 's' : 'science' }
Sub1.update(Sub2)
Sub1 # {'p': 'physics', 'c': 'chemistry', 'b': 'biology', 'e': 'english', 'h': 'hindi', 's': 'science'}
Subject for “e” replaced with “english”
Remove an element in a dictionary
Two commands are used to remove items from dictionary
a. del command
b. pop command
del command
Sub3 = {'p': 'physics', 'c': 'chemistry', 'b': 'biology', 'e': 'english', 'h': 'hindi', 's': 'science'}
del Sub3[‘b’]
Sub3 {'p': 'physics', 'c': 'chemistry', 'e': 'english', 'h': 'hindi', 's': 'science'}
pop command
Sub3 = {'p': 'physics', 'c': 'chemistry', 'e': 'english', 'h': 'hindi', 's': 'science'}
Sub3.pop(‘e’) This command will display item value after deleting it
‘english’
Sub3 {'p': 'physics', 'c': 'chemistry', 'h': 'hindi', 's': 'science'}
Membership operator ‘in’ and ‘not in’
Membership operator ‘in’ and ‘not in’ also used to check whether the key is available in
dictionary or not
Sub1 = {'p': 'physics', 'c': 'chemistry', 'b': 'biology', 'e': 'english', 'h': 'hindi', 's': 'science'}
‘p’ in Sub1 #True
‘r’ in Sub1 #False
‘t’ not in Sub1 #True
‘h’ not in Sub1 # False
Youtube channel : ipcsguide 2 Manish Kumar Gupta
DICTIONARY FUNCTIONS & METHODS
a. len( )
this function is count the number of key‐value pair in the dictionary
Dict1 = {'p': 'physics', 'c': 'chemistry', 'b': 'biology', 'e': 'english', 'h': 'hindi', 's': 'science'}
len(Dict1) #5
b. clear( )
Remove all items from the particular dictionary. Empty dictionary will exists
Dict5 = {'p': 'physics', 'c': 'chemistry', 'b': 'biology', 'e': 'english', 'h': 'hindi', 's': 'science'}
Dict5.clear( )
Dict5 #{}
c. get( )
Returns the value of key. If key does not exists, it will return None as default. We
can change the default value.
Syntax : dict.get(key, default = None)
Dict6 = {'p': 'physics', 'c': 'chemistry', 'b': 'biology', 'e': 'english', 'h': 'hindi', 's': 'science'}
Dict6.get(‘b’) # biology
Dict6.get(‘x’) #
Dict6.get(‘b’, ‘not available’) # biology
Dict6.get(‘x’, ‘not available’) # not available
d. items( )
returns the content of dictionary as list of tuples having key‐value pairs
dict1 = {1: 'table', 2 : 'chair', 3 : 'table'}
dict1.items( ) # dict_items([(1, 'table'), (2, 'chair'), (3, 'table')])
e. keys( )
return the key from key‐pair in the given dictionary
dict1 = {1: 'table', 2 : 'chair', 3 : 'table'}
dict1.keys( ) # dict_keys([1, 2, 3])
f. values( )
return the values from key‐pair in the given dictionary
dict1 = {1: 'table', 2 : 'chair', 3 : 'table'}
dict1.values( ) # dict_values(['table', 'chair', 'table'])
Q1. Whether dictionary is mutable or immutable. Give example.
Q2. Define the following functions with example in terms of dictionary.
get( ) clear( ) len( ) items( )
Q3. What are the two ways to delete items in a dictionary.
Q4. What is the error in the following : dict1 = (1: 100, 1: 1000, 2: 20, 2 : 2000)
Q5. Write a program in python to enter name of employee and age in a dictionary emp
Q6. Write a program in python to store item names and price of 5 items in a dictionary d11.
Youtube channel : ipcsguide 3 Manish Kumar Gupta