DICTIONARY IN PYTHON
Introduction:
Dictionary is a mutable, unordered collection of elements in the form of key:value pairs that associates keys to
values. Dictionaries in Python have a “key” and a “value of that key”. Thus dictionary is an organised collection
of data in the key:value form.
e.g.
D ={‘A’:10,’B’:20,’C’:30,’D’:40}
Features/Characteristics of a Dictionary:
The important features/characteristics of a dictionary are:
i) Each key in the dictionary is mapped to a particular value. Thus dictionary is an unordered set of key
value pairs.
ii) Each key is separated from its value by a colon (:), the items are separated by commas and the entire
dictionary is enclosed inside curly braces {}.
iii) Keys are unique within a dictionary and must be of immutable type.
iv) The values may not be unique and can be of any data type.
v) Dictionary is mutable. We can add new items or change the value of any existing key.
vi) Internally dictionary is indexed or arranged on the basis of keys.
Creating Dictionary:
Dictionary can be created in the following ways:
i) To create an empty dictionary:
Process-1:
>>> D1={}
>>> D1
{}
>>> type(D1)
<class 'dict'>
Process-2:
>>> D2=dict()
>>> D2
{}
>>> type(D2)
<class 'dict'>
The dict()is used to create a new dictionary.
ii) To add an item to an existing empty dictionary:
To add an item to the dictionary, we can use square brackets for accessing and initializing
dictionary values.
e.g.
>>> D=dict()
>>> D['Sameer']=19
>>> D['Kreeti']=21
>>> D
{'Sameer': 19, 'Kreeti': 21}
iii) Using the dict():
>>> DX=dict({'India':'New Delhi','Italy':'Rome','France':'Paris'})
>>> DX
{'India': 'New Delhi', 'Italy': 'Rome', 'France': 'Paris'}
Accessing the elements of a Dictionary:
To access to elements of the dictionary we can mention the key name in the square bracket of the
dictionary to obtain its value. If we attempt to access the value of a key which does not exist, then Python
raises keyError.
e.g.
>>> D={'India':'New Delhi','Italy':'Rome','France':'Paris'}
>>> D['Italy']
'Rome'
>>> D['England']
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
D['England']
KeyError: 'England'
Traversing a dictionary means accessing each element of a dictionary. This can be done using for loop.
Syntax:
for key in dictionary:
print(key, dictionary[key])
e.g.
D={'A':1,'B':2,'C':3,'D':4}
for x in D:
print(x,'-',D[x])
Output:
A-1
B-2
C-3
D–4
Write a Python Program to store names and marks obtained by the students in a dictionary and display
them in tabular form.
Ans:
D=dict()
n=int(input('How many records do you want?'))
for i in range(1,n+1):
name=input('Enter the Name:')
marks=int(input('Enter the Marks:'))
D[name]=marks
for key in D:
print('Name:',key,'\t','Marks:',D[key])
Output:
How many records do you want?3
Enter the Name: John
Enter the Marks: 85
Enter the Name: Bill
Enter the Marks: 76
Enter the Name: Sheena
Enter the Marks: 91
Name: John Marks: 85
Name: Bill Marks: 76
Name: Sheena Marks: 91
Adding a new item in a Dictionary:
We can add new elements to the existing dictionary by mentioning the new key in square bracket of the
dictionary and assinging its values-but the key being added must not exist in the dictionary.
e.g.
>>> DT={'A':10,'B':20,'C':30,'D':40}
>>> DT
{'A': 10, 'B': 20, 'C': 30, 'D': 40}
>>> DT['E']=50
>>> DT
{'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50}
Updating/Modifying an item in a Dictionary:
We can update a dictionary by modifying the value of a particular key by mentioning the key name in the
square bracket of the dictionary. If the key does not exist, then that key: value pair will be added to the
dictionary, otherwise the old value of that key will be updated with the new value.
e.g
>>> DT={'A':10,'B':20,'C':30,'D':40}
>>> DT['B']=100
>>> DT['C']=200
>>> DT
{'A': 10, 'B': 100, 'C': 200, 'D': 40}
Membership Testing in a Dictionary:
The membership operators ‘in’ and ‘not in’ return True or False depending on the existence of a
particular key in the dictionary.
e.g.
>>> D={'Fruit':'Mango','Vegetable':'Carrot','Colour':'Red','Vehicle':'Bus'}
>>> 'Colour' in D
True
>>> 'Mango' in D
False
>>> 'Tools' not in D
True
Commonly used Functions/Methods in a Dictionary:
i) len():
It returns the number of key:value pairs in the dictionary.
>>> D={'Fruit':'Mango','Vegetable':'Carrot','Colour':'Red','Vehicle':'Bus'}
>>> len(D)
4
ii) clear():
It removes all the items from a particular dictionary and makes the dictionary empty.
e.g.
>>> D={'Fruit':'Mango','Vegetable':'Carrot','Colour':'Red','Vehicle':'Bus'}
>>> len(D)
4
>>> [Link]()
>>> D
{}
>>> len(D)
0
iii) get():
It takes the key of the dictionary as argument and returns the corresponding value of that
key. If the key does not exist, then:
i) It returns a default value- if specified.
ii) It returns None , if the default value is not specified.
e.g.
>>> D={'A':1,'B':2,'C':3,'D':4,'E':5}
>>> [Link]('C')
3
>>> [Link]('P')
>>> [Link]('P',0)
0
iv) keys():
It returns the list of keys in the dictionary.
e.g.
>>> D={'A':1,'B':2,'C':3,'D':4,'E':5}
>>> [Link]()
dict_keys(['A', 'B', 'C', 'D', 'E'])
v) values():
It returns a list of values from key:values pairs in the dictionary.
e.g.
>>> D={'A':1,'B':2,'C':3,'D':4,'E':5}
>>> [Link]()
dict_values([1, 2, 3, 4, 5])
vi) items():
It returns the contents of dictionary as a tuple having key:values pairs.
e.g.
>>> D={'A':1,'B':2,'C':3,'D':4,'E':5}
>>> [Link]()
dict_items([('A', 1), ('B', 2), ('C', 3), ('D', 4), ('E', 5)])
vii) update ():
It merges key:value pairs from the new dictionary into the original dictionary, adding or replacing
as needed. If any key in the new dictionary is same as in the existing dictionary then the value
will be replaced, otherwise added.
e.g.
>>> D1={'India':10,'England':9,'Spain':18}
>>> D2={'France':7,'Belgium':21,'India':12}
>>> [Link](D2)
>>> D2
{'France': 7, 'Belgium': 21, 'India': 12}
>>> D1
{'India': 12, 'England': 9, 'Spain': 18, 'France': 7, 'Belgium': 21}
viii) pop():
The pop() takes the key of the key:value pair as argument and deletes the element
accordingly. It returns the value of key:value pair to be deleted. If the keyname does not
exist-Python raises Keyerror.
e.g.
>>> DT={'A':10,'B':20,'C':30,'D':40}
>>> [Link]('D')
40
>>> DT
{'A': 10, 'B': 20, 'C': 30}
>>> [Link]('T')
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
[Link]('T')
KeyError: 'T'
ix) del Statement:
The del statement requires the dictionary name and the key of the key:value pair to be
deleted. The key name should be passed in the square bracket of the dictionary. If the
keyname does not exist-Python raises Keyerror.
e.g.
>>> DT={'A':10,'B':20,'C':30,'D':40}
>>> DT
{'A': 10, 'B': 20, 'C': 30, 'D': 40}
>>> del DT['C']
>>> DT
{'A': 10, 'B': 20, 'D': 40}
>>> del DT['T']
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
del DT['T']
KeyError: 'T'
x) fromkeys():
The fromkeys() method creates a new dictionary from the given sequence of elements with a value
provided by the user.
Syntax:
newdictionary=[Link](sequence,<value>)
e.g.
>>> D={'A':1,'B':2,'C':3,'D':4,'E':5}
>>> val=20
>>> newD=[Link](D,val)
>>> newD
{'A': 20, 'B': 20, 'C': 20, 'D': 20, 'E': 20}
xi) copy():
The copy() is used to create a new dictionary which is filled with a copy of the references from the
original dictionary. If the original dictionary is modified- the new copy dictionary is not affected.
e.g.
>>> D={'A':1,'B':2,'C':3,'D':4,'E':5}
>>> T=[Link]()
>>> T
{'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}
>>> D['A']=100
>>> D
{'A': 100, 'B': 2, 'C': 3, 'D': 4, 'E': 5}
>>> T
{'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}
xii) popitem():
The popitem () method removes and returns the item that was inserted into the dictionary at last.
Syntax:
[Link]()
e.g.
>>> D={'A':1,'B':2,'C':3,'D':4,'E':5}
>>> [Link]()
('E', 5)
>>> D
{'A': 1, 'B': 2, 'C': 3, 'D': 4}
xiii) setdefault():
The setdefault() method returns the value of a key (if the key is in dictionary). If not, it inserts thw
key with a value to the dictionary.
Syntax:
[Link](key,<value>)
e.g.
>>> A={'AB':100,'CD':200,'EF':300,'GH':400}
>>> [Link]('EF')
300
>>> [Link]('IJ',1000)
1000
>>> A
{'AB': 100, 'CD': 200, 'EF': 300, 'GH': 400, 'IJ': 1000}
xiv) max():
The max() returns the largest key in the dictionary. The largest key is decided based on the sequence
of the characters i.e. the order of characters.
xv) min():
The min() returns the smallest key in the dictionary. The smallest key is decided based on the
sequence of the characters i.e. the order of characters.
e.g.
>>> country={'India':'New Delhi','England':'London','Italy':'Rome','France':'Paris'}
>>> max(country)
'Italy'
>>> min(country)
'England'
xvi) sorted():
The sorted() takes a dictionary as argument and returns a list containing the keys of the dictionary
sorted in the ascending order of their alphabetical values. If the “reverse” argument in the sorted()
is set to True, then the list contains the keys of the dictionary sorted in the descending order of their
alphabetical values.
e.g.
A={'LENOVO':143,'MICROSOFT':249,'DELL':91,'HP':372,'SONY':266}
>>> sorted(A)
['DELL', 'HP', 'LENOVO', 'MICROSOFT', 'SONY']
>>> sorted(A,reverse=True)
['SONY', 'MICROSOFT', 'LENOVO', 'HP', 'DELL']
Program-1:
Write a Python Program to store class-section information in a list and count the frequency of elements
in the list using a dictionary.
Ans:
D=dict()
L=list()
n=int(input('Enter the number of class/sections:'))
for i in range(1,n+1):
info=input('Enter the class and section:')
[Link](info)
for item in L:
key=item
if(key not in D):
c=[Link](key)
D[key]=c
print('----------FREQUENCY OF ELEMENTS-------')
for item in D:
print(item,'Present',D[item],'times')
Output:
Enter the number of class/sections:6
Enter the class and section:12D
Enter the class and section:11C
Enter the class and section:11C
Enter the class and section:12C
Enter the class and section:11F
Enter the class and section:11F
----------FREQUENCY OF ELEMENTS-------
12D Present 1 times
11C Present 2 times
12C Present 1 times
11F Present 2 times
Program-2:
Write a Python Program to store the name and salary of ‘n’ number of employees of an organisation in a
dictionary and display the details of the employees whose salary is above 30000.
Ans:
emp=dict()
n=int(input('How many records do you want to enter?'))
for i in range(1,n+1):
name=input('Enter the name:')
sal=int(input('Enter the salary:'))
emp[name]=sal
print('The Details of the employees whose salary is above 30000:')
for key in emp:
if(emp[key]>30000):
print(key,'draws the salary of Rs',emp[key])
----------------------------------