Dictionary
Dictionary
It is an unordered collection of items where
each item consist of a key and a value.
It is mutable (can modify its contents ) but Key must
be unique and immutable.
Dictionary
Creating A Dictionary
It is enclosed in curly braces {} and each item is separated from other item by a
comma(,). Within each item, key and value are separated by a colon (:).Passing
value in dictionary at declaration is dictionary initialization.get() method is used to
access value of a key
e.g.
dict = {‘Subject': ‘Informatic Practices', 'Class': ‘11'}
Accessing List Item
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print(dict)
print ("Subject : ", dict['Subject'])
print ("Class : ", dict.get('Class'))
OUTPUT
{'Class': '11', 'Subject':
'Informatics Practices'}
('Subject : ', 'Informatics
Practices')
('Class : ', 11)
Dictionary
Iterating / Traversing through A Dictionary
Following example will show how dictionary items can be accessed through loop.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
for i in dict:
print(dict[i])
OUTPUT
11
Informa
tics
Practice
s
Updat
ing/
Mani
pulati
ng
Dictionary
Deleting Dictionary Elements
del, pop() and clear() statement are used to remove
elements from the dictionary.
del e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
del dict['Class'] # delete single element
print('after item delete', dict)
del dict #delete whole dictionary
print('after dictionary delete', dict)
Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after dictionary delete', <type 'dict'>)
Dictionary
pop() method is used to remove a particular item in a
dictionary. clear() method used to remove all
is elements from the
dictionary.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
dict.pop('Class')
print('after item delete', dict)
dict.clear()
print('after clear', dict)
Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after clear', {})
Dictionary
Built-in Dictionary Functions
S.No. Function & Description
len(dict)Gives the total length of the dictionary. It is equal to
the number of items in the dictionary.
1 dict = {'Name': 'Aman', 'Age': 37};
print ("Length : %d" % len (dict))
OUTPUT ->2
str(dict)Return a printable string representation of
2 a
dictionary
type(variable)If variable is dictionary, then it would return a
dictionary type.
3
Dictionary
Built-in Dictionary Methods
S.No. Method & Description
dict() - creates dictionary
1 x = dict(name = “Aman", age = 37, country = “India")
Here x is created as dictionary
keys() - returns all the available keys
x = dict(name = “Aman", age = 37, country = “India")
2 print(x.keys())
OUTPUT->dict_keys(['country', 'age', 'name'])
values() - returns all the available values
x = dict(name = “Aman", age = 37, country = “India")
3 print(x.values())
OUTPUT->dict_values(['India', 37, 'Aman'])
Dictionary
Built-in Dictionary Methods
S.No. Method & Description
items() - return the list with all dictionary keys with values.
x = dict(name = "Aman", age = 37, country = "India")
4 print(x.items())
OUTPUT->dict_items([('country', 'India'), ('age', 37),
('name', 'Aman')])
update()-used to change the values of a key and add new keys x
= dict(name = "Aman", age = 37, country = "India")
d1 = dict(age= 39)
5 x.update(d1,state="Rajasthan")
print(x)
OUTPUT-{'country': 'India',
'age': 39,'name':'Aman','state':
'Rajasthan'}
Dictionary
Built-in Dictionary Methods
S.No. Method & Description
del -used to remove key
x = dict(name = "Aman", age = 37, country = "India")
del x['age']
6 print(x)
OUTPUT-
>{'country'
: 'India',
'name':
'Aman'}
del x ->
will
remove
complete
dictionary
fromkeys() – is used to create dictionary from keys
keys = {'a', 'e', 'i', 'o', 'u' }
Dictionary
Built-in Dictionary Methods
S.No. Method & Description
copy() - returns a shallow copy of the dictionary.
x = dict(name = "Aman", age = 37, country = "India")
y=x.copy()
print(y)
print(id(x))
8 print(id(y))
OUTPUT - >{'country': 'India', 'age': 37, 'name':
'Aman'}
33047872
33047440
popitem() – removes last item from dictionary
x = dict(name = "Aman", age = 37, country = "India")
9 x.popitem()
print(x)
OUTPUT->
{'age': 37,
'name':
'Aman'}
Dictionary
Built-in Dictionary Methods
S.No. Method & Description
setdefault() method returns the value of the item with the specified key.
If the key does not exist, insert the key, with the specified value.
x = dict(name = "Aman", country = "India")
10 y=x.setdefault('age',39)
print(y)
OUTPUT-> 39
max() – returns key having maximum value
Tv = {'a':100, 'b':1292, 'c' : 88}
11 Keymax = max(Tv, key=Tv.get)
print(Keymax
) OUTPUT-> b
12 min()- returns key having minimum value
Dictionary
Built-in Dictionary Methods
S.No. Method & Description
sorted- sort by key or value
dict1 = {'b':100, 'a':12, 'c' : 88}
13 y = sorted(dict1.items(),key=lambda x: x[1],reverse=True)
print(y)
OUTPUT-> [('b', 100), ('c', 88), ('a', 12)]
Dictionary
create a dictionary with names of employees, their
salary and access them
employees =
{'Aman':{'salary':'10000'},'Mayur':{'salary':'51000'}}
employee1 = employees['Aman']
print(employee1)
OUTPUT
{'salary': '10000'}
Dictionary
Questions.
1. Create dictionary to store 4 student details with
rollno,name,age field.Search student in list.