You are on page 1of 137

{Dictionaries}

{Key:value}

MUTABLE DATA TYPE


• The data type dictionary fall under mapping.
• A mapping object maps immutable values to arbitrary objects.
• It is a mapping between a set of keys and a set of values. The key-
value pair is called an item.
• A key is separated from its value by a colon(:) and consecutive items
are separated by commas.
• Items in dictionaries are unordered (versions earlier than 3.7), so we
may not get back the data in the same order in which we had entered
the data initially in the dictionary.

dict3 = {'Mohan':95,'Ram':89,'Suhel':92}
dict3 = {'Mohan':95,'Ram':89,'Suhel':92}

Ram 89

Mohan 92

Suhel 95

Mapping/hash table

Internally, the key:value pairs of a dictionary are associated with one another with some internal function (called hash-
function). This way of linking is called mapping.
Creating a Dictionary

• To create a dictionary, the items entered are separated by commas and


enclosed in curly braces.
• Each item is a key value pair, separated through colon (:).
• The keys in the dictionary must be unique and should be of any immutable
data type, i.e., number, string or tuple.
• The values can be repeated and can be of any data type.

#dict1 is an empty Dictionary created


#curly braces are used for dictionary
>>> dict1 = {}
>>> dict1
{}
#dict2 is an empty dictionary created using built-in function
>>> dict2 = dict()
>>> dict2
{}
Creating a Dictionary

• To create a dictionary, the items entered are separated by commas and


enclosed in curly braces.
• Each item is a key value pair, separated through colon (:).
• The keys in the dictionary must be unique and should be of any immutable
data type, i.e., number, string or tuple.
• The values can be repeated and can be of any data type.

#dict3 is the dictionary that maps names of the students


to respective marks in #percentage
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> dict3
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85}
Accessing Items in a Dictionary
• The items of a sequence (string, list and tuple) are accessed using a technique called
indexing.
• The items of a dictionary are accessed via the keys rather than via their relative positions or
indices.
• Each key serves as the index and maps to a value. The following example shows how a
dictionary returns the value corresponding to the given key:
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict3['Ram']
89
>>> dict3['Sangeeta'] The dictionary operation that takes
85 a key and finds the corresponding
#the key does not exist value, is called lookup
>>> dict3['Shyam']
KeyError: 'Shyam'
In the above examples the key 'Ram' always maps to the value 89 and key 'Sangeeta'
always maps to the value 85. So the order of items does not matter. If the key is not present in
the dictionary we get KeyError.
Dictionaries are Mutable
Dictionaries are mutable which implies that the contents of the dictionary can be changed after it has been created.

Adding a new item Modifying an Existing Item


Adding a new item
We can add a new item to the dictionary as shown in
the following example:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> dict1['Meena'] = 78
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,
'Sangeeta': 85, 'Meena': 78}
Modifying an Existing Item
The existing dictionary can be modified by just overwriting the key-
value pair.
Example to modify a given item in the dictionary:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
#Marks of Suhel changed to 93.5
>>> dict1['Suhel'] = 93.5
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5,
'Sangeeta': 85}
Membership
The membership operator in checks if the key is present in the dictionary
and returns True, else it returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> 'Suhel' in dict1
True

The not in operator returns True if the key is not present in


the dictionary, else it returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> 'Suhel' not in dict1
False
Traversing a Dictionary
We can access each item of the dictionary or traverse a dictionary
using for loop.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
Method 1
for key in dict1:
print(key,':',dict1[key])
OUTPUT
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Traversing a Dictionary
We can access each item of the dictionary or traverse a dictionary
using for loop.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
Method 1
for key in dict1:
print(key,':',dict1[key])
OUTPUT
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Dictionary methods
and
Built-in functions
len()
Returns the length or number of key: value pairs of the
dictionary passed as the argument

>>> dict1 = {'Mohan':95,'Ram':89,


'Suhel':92, 'Sangeeta':85}
>>> len(dict1)
4
dict()

Creates a dictionary from a sequence of key-value pairs


Using a list of tuples
pair1 = [('Mohan',95),('Ram',89),('Suhel’,92)]
>>> pair1
[('Mohan', 95), ('Ram', 89), ('Suhel',92)]
>>> dict1 = dict(pair1)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92}
dict()

Creates a dictionary from a sequence of key-value pairs


Using a tuple of tuples
>>> pair1=(('Mohan', 95), ('Ram', 89), ('Suhel',92))
>>> dict1 = dict(pair1)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92}
dict()

Creates a dictionary from a sequence of key-value pairs


Using a tuple of lists
>>> pair1=(['Mohan', 95], ['Ram', 89], ['Suhel',92])
>>> dict1 = dict(pair1)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92}
dict()

Creates a dictionary from a key-value pairs passed as


keyword arguments to dict() function

>>> dict1=dict(Mohan= 95, Ram= 89, Suhel=92)


>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92}

>>> dict1=dict('Mohan'= 95, 'Ram'= 89, 'Suhel'=92) #keys enclosed in quotes


SyntaxError: keyword can't be an expression
keys()

Returns a list of keys in the dictionary


>>>dict1={'Mohan':95,'Ram':89,'Suhel':92}
>>> dict1.keys()
dict_keys(['Mohan', 'Ram', 'Suhel'])

You can convert the sequence returned by keys() and values() functions by
using list() as shown below:

>>>list(dict1.keys())
['Mohan', 'Ram', 'Suhel']
values()

Returns a list of values in the dictionary


>>> dict1 = {'Mohan':95, 'Ram':89,
'Suhel':92, 'Sangeeta':85}
>>> dict1.values()
dict_values([95, 89, 92, 85])
items()

Returns a list of tuples(key – value) pair


>>> dict1 = {'Mohan':95, 'Ram':89,
'Suhel':92, 'Sangeeta':85}
>>> dict1.items()
dict_items([( 'Mohan', 95), ('Ram',
89), ('Suhel', 92), ('Sangeeta', 85)])
get()

Returns the value corresponding to the key passed as the Argument.


>>> dict1 = {'Mohan':95, 'Ram':89,
'Suhel':92, 'Sangeeta':85}
>>> dict1.get('Sangeeta')
85
If the key is not present in the dictionary it will return None
>>> dict1.get('Sohan')
>>>

Dict[key] returns error, if key is not found


Syntax:
<dictionary>.get(key,[default])

Dict.get(key) is equivalent to Dict[Key]

Dict[key] returns error, if key is not found


update()

Appends the key-value pair of the dictionary passed as the argument to


the key-value pair of the given dictionary
>>> dict1 = {'Mohan':95, 'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> dict2 = {'Sohan':79,'Geeta':89}
>>> dict1.update(dict2)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta':
85, 'Sohan': 79, 'Geeta':89}
>>> dict2
{'Sohan': 79, 'Geeta': 89}
del()

Deletes the item with the given key. To delete the dictionary from the memory
we write: del Dict_name
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85} It returns KeyError if key is
>>> del dict1['Ram'] not existing in the
>>> dict1 dictionary
{'Mohan':95,'Suhel':92, 'Sangeeta': 85}
>>> del dict1 ['Mohan']
>>> d={1:2,3:4,5:6}
>>> dict1 >>> del d[3],d[5]
>>> d
{'Suhel': 92, 'Sangeeta': 85} {1: 2}
>>> del dict1 >>>
>>> dict1
NameError: name 'dict1' is not defined
clear()

Deletes or clear all the items of the dictionary


>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> dict1.clear()
>>> dict1
{ }
If Key is not found, then generates KeyError
>>> dict= {'Subject': 'Informatics Practices', 'Class': 11}
>>> dict.pop()
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
dict.pop()
TypeError: pop expected at least 1 arguments, got 0

>>> dict.pop('Subject’) #returns the value


'Informatics Practices'
>>> dict #note the item removed from the dict
{'Class': 11}
>>>
If Key not found,
then generates
KeyError
Giving custom error message

M=Car.pop(“Color”, “Not here”)

‘Not here’
Can give integer value too instead of message

M=Car.pop(“Color”, -1)

-1
Works on LIFO principle

If the dictionary is empty, it returns KeyError

as tuple of
key and
value
popitem() takes no argument

Xii d 28/8

as tuple of
key and
value
str(dict)
Return a printable string representation of a dictionary

>>> dict1= {'Subject': 'Informatics Practices', 'Class': 11}


>>> str(dict1)
"{'Subject': 'Informatics Practices', 'Class': 11}"
>>>
type(variable)
If variable is dictionary, then it would return a dictionary type

>>> dict1= {'Subject': 'Informatics Practices', 'Class': 11}


>>> type(dict1)
<class 'dict'>
>>>
>>> nd=dict.fromkeys([2,4,6,8],100)
>>> nd
{2: 100, 4: 100, 6: 100, 8: 100}
>>> nd1=dict.fromkeys((3,4,5))
>>> nd1
{3: None, 4: None, 5: None}
nd1=dict.fromkeys((3,4,5),(6,7,8)) The entire tuple(6,7,8) has
been considered as 1 element
>>> nd1 here.
{3: (6, 7, 8), 4: (6, 7, 8), 5: (6, 7, 8)}
>>> nd1=dict.fromkeys((3,4,5),[2,3])
>>> nd1 The entire list[2,3] has been
considered as 1 element here.
{3: [2, 3], 4: [2, 3], 5: [2, 3]}
>>>nd1=dict.fromkeys((3,4,5),[2:3])
>>>nd1
>>> nd=dict.fromkeys([2,4,6,8],100)
>>> nd
{2: 100, 4: 100, 6: 100, 8: 100}
>>> nd1=dict.fromkeys((3,4,5))
>>> nd1
{3: None, 4: None, 5: None}
nd1=dict.fromkeys((3,4,5),(6,7,8)) #it has given the tuple(6,7,8) as the value for
>>> nd1 all the keys as it was given at the place of the
{3: (6, 7, 8), 4: (6, 7, 8), 5: (6, 7, 8)} value argument
>>> nd1=dict.fromkeys((3,4,5),[2,3])
>>> nd1
{3: [2, 3], 4: [2, 3], 5: [2, 3]}
>>>nd1=dict.fromkeys((3,4,5),[2:3])
>>>nd1
NOTE: keys argument must be an iterable sequence, even if you have a single key, e.g., the
following statements will raise error

>>> nd2=dict.fromkeys(3) >>> nd2=dict.fromkeys(3,)


Traceback (most recent call last): Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module> File "<pyshell#10>", line 1, in <module>
nd2=dict.fromkeys(3) nd2=dict.fromkeys(3,)
TypeError: 'int' object is not iterable TypeError: 'int' object is not iterable
NOTE: if you have a single element iterable, then you should give it in tuple or list form as
shown
>>> nd2=dict.fromkeys((3,)) >>> nd2=dict.fromkeys([3])
>>> nd2 >>> nd2
{3: None} {3: None}
>>> n=dict.fromkeys("hello")
>>> n
{'h': None, 'e': None, 'l': None, 'o': None}
Application of fromkeys()

Your school has decided to deposit scholarship amount of Rs2500 to some


selected students. Write a python script to input the selected students
admission number and create a dictionary for the same

#read adm numbers in a list L


S=dict.fromkeys(L,2500)
>>>L2=sorted(D.items()) Returns a list
>>>L2 in ascending
[('P1', 65), ('P2', 34), ('P3', 45), ('P4', 56)] order of keys
>>> L2=sorted(D.items(),reverse=True)
>>> L2 Returns a list
[('P4', 56), ('P3', 45), ('P2', 34), ('P1', 65)] in descending
order of keys

Result of sorted
function typecasted to
dictionary
Extend/Update dictionary with new key:value pairs

Using setdefault() method


Using update() method
Other dictionary
This method inserts a new key:value pair ONLY IF the key
doesn’t already exists.
>>> a={1:"A",2:"B",3:"C"}
>>> print(a.setdefault(3)) #returned value ‘C’ as key was already existing
C
>>> a
{1: 'A', 2: 'B', 3: 'C’} #no changes made to dictionary

>>> a.setdefault(4) #key 4 added to dictionary with none as value


>>> a
{1: 'A', 2: 'B', 3: 'C', 4: None}

>>> a.setdefault(5,"not known") #key:value pair added to the dictionary


'not known'
>>> a
{1: 'A', 2: 'B', 3: 'C', 4: None, 5: 'not known'}
Predict the output????

>>> d1={}
>>> val1=d1.setdefault(30,'r')
>>> val2=d1.setdefault(30,'rr')
>>> val3=d1.setdefault(40)
>>> print(val1,val2,val3)
Predict the output????

>>> d1={}
>>> val1=d1.setdefault(30,'r')
>>> val2=d1.setdefault(30,'rr')
>>> val3=d1.setdefault(40)
>>> print(val1,val2,val3)
r r None
Predict the output????

>>> new_dict={}
>>> for i in range(5):
new_dict.setdefault(i)
>>> print(new_dict)
Predict the output????

>>> new_dict={}
>>> for i in range(5):
new_dict.setdefault(i)
>>> print(new_dict)
{0: None, 1: None, 2: None, 3: None, 4: None}
Will fetch max/min
key value pair
Will fetch only
max/min key

Will fetch only


max/min value

Lowest
Lowest
For min(), max() and sum() functions to work, the dictionary keys must be of homogenous types
>>> d1={(1,2):'one',(3,4):'two'}
>>> d2={'Green House':20,'Blue House':30}
>>> d3={41:'N',12:'S',32:'A'} >>> min(d1),min(d2),min(d3),min(d4)
((1, 2), 'Blue House', 12, 1.5)
>>> d4={1.5:'N',3.5:'s'} >>> max(d1),max(d2),max(d3),max(d4)
((3, 4), 'Green House', 41, 3.5)
>>> sum(d1)
Traceback (most recent call last):
Consider the declaration File "<pyshell#22>", line 1, in <module>
of 4 different dictionaries sum(d1)
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
>>> sum(d2)
>>> t1=(2,1)
>>> t2=(2,0)
Traceback (most recent call last):
>>> min(t1,t2) File "<pyshell#23>", line 1, in <module>
(2, 0) sum(d2)
>>> t1=(2,1,3) TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> t2=(2,1) >>> sum(d3)
>>> min(t1,t2) 85 sum() function worked with dictionaries
(2, 1) d3 and d4 as these dictionaries have
>>> sum(d4)
key types compatible for addition
5.0
Try!!!!!
>>> numbers={1:111,2:222,3:333,4:444}
>>> m1=max(numbers)
>>> m2=min(numbers)
>>> m3=max(numbers.values())
>>> m4=min(numbers.values())
>>> m5=sum(numbers)
>>> m6=sum(numbers.values())
>>> m7=max(numbers.items())
>>> print(m1,m2,m3,m4,m5,m6,m7)
Try!!!!!
>>> numbers={1:111,2:222,3:333,4:444}
>>> m1=max(numbers)
>>> m2=min(numbers)
>>> m3=max(numbers.values())
>>> m4=min(numbers.values())
>>> m5=sum(numbers)
>>> m6=sum(numbers.values())
>>> m7=max(numbers.items())
>>> print(m1,m2,m3,m4,m5,m6,m7)
4 1 444 111 10 1110 (4, 444)
When assignment operator is used
When copy() is used for copying
for copying list/tuple/dictionary,
list/tuple/dictionary, both objects refer
both objects refer to same memory Important to different memory locations
location concept
>>> l1=[1,2]
>>> l1=[1,2] >>> l2=l1.copy()
>>> l2=l1 >>> id(l1),id(l2)
>>> id(l1),id(l2) (58517344, 14788288)
(58516744, 58516744) >>> t1=(1,2)
>>> t1=(1,2) >>> t2=(3,4)
>>> t2=t1 >>> id(t1),id(t2)
>>> id(t1),id(t2) (14803272, 14769608)
(64851480, 64851480) >>> d1={1:2,3:4}
>>> d1={1:2,3:4} >>> d2=d1.copy()
>>> d2=d1 >>> id(d1),id(d2)
>>> id(d1),id(d2) (14757824, 14757728)
(60230368, 60230368)
Copy() :Creates separate copy of object in memory so that
changes made to one object are not reflected to other

Called DEEP copy


(equivalent to call by
value concept of c++

>>> d1={1:2,3:4} Note the ID of {1:2,3:4}


>>> d2=d1.copy() the two d1
>>> id(d1),id(d2) dictionaries
d2=d1.copy()
(66335968, 66336112)
{1:2,3:4}
d2
Creates reference of object in memory so that changes made to
one object are reflected for other. Called SHALLOW copy
(equivalent to call by
reference concept of c++

>>> d1={1:2,3:4}
>>> d2=d1.copy()
>>> id(d1),id(d2) #deep copy
(66335968, 66336112) d1
>>> d3=d1 Note the id’s of the two
>>> id(d1),id(d3) #shallow copy dictionaries are same here d2=d1 {1:2,3:4}
(66335968, 66335968)
>>> d2
Using =
Using copy()

In shallow copy, only keys are copied not the values.


In deep copy, both keys and values are copied and a Hence changes made to one dictionary would be
new object is created. Hence changes made to one reflected to other as well…even if you add a new key
object do not reflect in other. value pair
Though we have used copy() function in both the examples TO
CREATE DEEP COPY OF OBJECT, but note the following differences

If the values are immutable, changes made to one are not reflected
in the other

If the values are mutable, changes made to one are reflected in the
other

Still if you don’t want python to


make changes to your deep copy
then you may use deepcopy() [NOT
IN SYLLABUS]
A program to check if a dictionary is empty

>>> d={}
#to check a dictionary is empty or not >>> bool(d)
False
dict1 = {} >>> d={1:2}
>>> bool(d)
if not bool(dict1): True
print("Dictionary is empty")
Alternate code:
>>> d={}
>>> if len(d)==0:
print("empty")
#make a dictionary using constructor

dict1 = dict("MANGO": "YELLOW", "APPLE": "RED",


"GUAVAVA": "GREEN")
print(dict1)
#concatenate dictionaries to create a new one

dict1={1:'AMIT', 2:'VISHAL'}
dict2={3:'MOHAK'}
dict3 = {}
for d in (dict1, dict2):
dict3.update(d)
print(dict3)
#to create a dictionary where the keys are numbers between 1 to
10 and the values are square of keys

dict1=dict()
for x in range(1,11):
dict1[x]=x**2
print(dict1)
#to sum all the values of a dictionary

dict1 = {'data1':1,'data2':2,'data3':3}
r=sum(dict1.values())
print(r)
#to map two lists into a dictionary

keys = ["banana", "apple"]


values = ["yellow","red"]
dict = dict(zip(keys, values))
print(dict)
#to print sorted dictionary by key

>>> dict ={ "MANGO": "YELLOW", "APPLE": "RED", "GUAVA": "GREEN"}


>>> for key in sorted(dict):
print(key, dict[key])

OUTPUT
APPLE RED
GUAVA GREEN >>> d={'Subject': 'Informatics Practices', 'Class': 11}
MANGO YELLOW >>> sorted(d)
>>> ['Class', 'Subject']
Declare/create a dictionary ‘ODD’ of odd numbers between 1 and 10, where the
key is the decimal number and the value is the corresponding number in words.
Declare/create a dictionary ‘ODD’ of odd numbers between 1 and 10, where the
key is the decimal number and the value is the corresponding number in words.

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
Perform the following operations on this dictionary:

(a) Display the keys


(b) Display the values
(c) Display the items
(d) Find the length of the dictionary
(e) Check if 7 is present or not
(f) Check if 2 is present or not
(g) Retrieve the value corresponding to the key 9
(h) Delete the item from the dictionary corresponding to the key 9
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
Perform the following operations
on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
(a) Display the keys
Perform the following operations
on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
(a) Display the keys

>>> ODD.keys()
dict_keys([1, 3, 5, 7, 9])
Perform the following operations
on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}

(b) Display the values


Perform the following operations
on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}

(b) Display the values

>>> ODD.values()
dict_values(['One', 'Three', 'Five', 'Seven', 'Nine'])
Perform the following operations
on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}

(c) Display the items


Perform the following operations
on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}

(c) Display the items


>>> ODD.items()
dict_items([(1, 'One'), (3, 'Three'), (5, 'Five'), (7,
'Seven'),(9, 'Nine')])
Perform the following operations
on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}

(d) Find the length of the dictionary


Perform the following operations
on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}

(d) Find the length of the dictionary


>>> len(ODD)
5
Perform the following operations on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}

(e) Check if 7 is present or not


Perform the following operations on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}

(e) Check if 7 is present or not


>>> 7 in ODD
True
Perform the following operations on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}

(f) Check if 2 is present or not


Perform the following operations on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}

(f) Check if 2 is present or not


>>> 2 in ODD
False
Perform the following operations on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
(g) Retrieve the value corresponding to the key 9
Perform the following operations on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
(g) Retrieve the value corresponding to the key 9
>>> ODD.get(9)
'Nine'
Perform the following operations on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}

(h) Delete the item from the dictionary corresponding to the key 9
Perform the following operations on this dictionary:

>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}

(h) Delete the item from the dictionary corresponding to the key 9
>>> del ODD[9]
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven'}
Write a program to enter names of employees and their
salaries as input and store them in a dictionary.
Output:
Enter the number of employees to be stored: 5
Enter the name of the Employee: 'Tarun'
Enter the salary: 12000
Enter the name of the Employee: 'Amina'
Enter the salary: 34000
Enter the name of the Employee: 'Joseph'
Enter the salary: 24000
Enter the name of the Employee: 'Rahul'
Enter the salary: 30000
Enter the name of the Employee: 'Zoya'
Enter the salary: 25000
EMPLOYEE_NAME SALARY
'Tarun' 12000
'Amina' 34000
'Joseph' 24000
'Rahul' 30000
'Zoya' 25000
Write a program to enter names of employees and their
salaries as input and store them in a dictionary.
num = int(input("Enter the number of employees whose data to be
stored: "))
count = 1
employee = dict() #create an empty dictionary
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])
Write a program to create a dictionary to store and count the number of
times a character appears in a given string.
For example if the string is HelloWorld the dictionary should be
Enter a string: HelloWorld
{'H': 1, 'e': 1, 'l': 3, 'o': 2, 'W': 1, 'r': 1, 'd': 1}
Write a program to create a dictionary to store count the number of times a
character appears in a given string.
For example if the string is HelloWorld the dictionary should be
Enter a string: HelloWorld
{'H': 1, 'e': 1, 'l': 3, 'o': 2, 'W': 1, 'r': 1, 'd': 1}
st = input("Enter a string: ")
d = {} #creates an empty dictionary
for ch in st:
if ch in d: #if next character is already in the dictionary
d[ch] += 1
else:
d[ch] = 1 #if ch appears for the first time
print(d)
#OTHER WAY OF WRITING PREVIOUS QUESTION
#to create a dictionary from a string with frequency of letters

str1 = 'computer science'


dict = {}
for letter in str1:
dict[letter] = dict.get(letter, 0) + 1
print(dict)

get() function returns None if key is not found. 0 would overwrite the default value None in
that case.
Write a program to create a dictionary where keys would be the
elements and their values would be the count of their frequency

=============== RESTART: C:/python37/class 11/dictionary/4.py


===============
list is: [1, 12, 3, 3, 12, 4]
dictionary is: {1: 1, 12: 2, 3: 2, 4: 1}
Write a program to create a dictionary where keys would be the
elements and their values would be the count of their frequency

=============== RESTART: C:/python37/class 11/dictionary/4.py


===============
list is: [1, 12, 3, 3, 12, 4] lst=[1,12,3,3,12,4]
dictionary is: {1: 1, 12: 2, 3: 2, 4: 1} d={}
print("list is:",lst)

for ele in lst:


try:
d[ele]+=1
except KeyError:
d[ele]=1
print("dictionary is:",d)
Write a function to convert a number entered by the user into its
corresponding number in words. For example, if the input is 876 then
the output should be ‘Eight Seven Six’.

Output:
Enter any number: 6512
The number is: 6512
The numberName is: Six Five One Two
Write a function to convert a number entered by the user into its
corresponding number in words. For example, if the input is 876 then
the output should be ‘Eight Seven Six’.
def convert(num):
numNames={0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',5:'Five',6:'Six’,
7:'Seven',8:'Eight',9:'Nine’}
result = ‘’
for ch in num: Output:
key = int(ch) #converts character to integer Enter any number: 6512
value = numNames[key] The number is: 6512
result = result + ' ' + value The numberName is: Six Five One
Two
return result

num = input("Enter any number: ") #number is stored as string


result = convert(num)
print("The number is:",num)
print("The numberName is:",result)
Consider the following dictionary stateCapital:
stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
Find the output of the following statements:
i. print(stateCapital.get("Bihar"))
ii. print(stateCapital.keys())
iii. print(stateCapital.values())
iv. print(stateCapital.items())
v. print(len(stateCapital))
vi print("Maharashtra" in stateCapital)
vii. print(stateCapital.get("Assam"))
viii. del stateCapital["Andhra Pradesh"]
print(stateCapital)
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}

>>> print(stateCapital.get("Bihar"))
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}

>>> print(stateCapital.get("Bihar"))
Patna
>>>
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.keys())
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.keys())
dict_keys(['AndhraPradesh', 'Bihar', 'Maharashtra', 'Rajasthan'])
>>>
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}

>>> print(stateCapital.values())
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}

>>> print(stateCapital.values())
dict_values(['Hyderabad', 'Patna', 'Mumbai', 'Jaipur'])
>>>
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.items())
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.items())
dict_items([('AndhraPradesh', 'Hyderabad'), ('Bihar', 'Patna'),
('Maharashtra', 'Mumbai'), ('Rajasthan', 'Jaipur')])
>>>
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(len(stateCapital))
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(len(stateCapital))
4
>>>
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print("Maharashtra" in stateCapital)
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print("Maharashtra" in stateCapital)
True
>>>
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.get("Assam"))
???

>>> stateCapital = {"AndhraPradesh":"Hyderabad",


"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.get("Bihar"))
???
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.get("Assam"))
None
>>>

>>> stateCapital = {"AndhraPradesh":"Hyderabad",


"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.get("Bihar"))
Patna
>>>
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> del stateCapital["AndhraPradesh"]
>>> print(stateCapital)
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> del stateCapital["AndhraPradesh"]
>>> print(stateCapital)
{'Bihar': 'Patna', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur'}
>>>
Write a Python program to find the highest 3 values in a dictionary.
Write a Python program to find the highest 3 values in a dictionary.

d={'a':5,'b':2,'c':10,'d’:7}
sorted(d.values(), reverse=True)[:3]

OUTPUT
[10, 7, 5]
Predict the output, if any??

>>>d={[1,2]: “abc”}
>>>d
Predict the output, if any??

>>>d={[1,2]: “abc”}
>>>d

:
TypeError:unhashable type: ‘list’

The above error always means that you have tried to assign a
key with mutable type and Python dictionaries do not allow
this.
Storing a dictionary inside another dictionary is called Nesting Dictionaries
nesting of dictionaries.
A dictionary contains details of two workers with their names as
Note: You can store a
keys and other details in the form of dictionary as value. WAP to dictionary as a value only,
print the workers’ information in records format. inside a dictionary. You cannot
have a key of dictionary
>>> emp={'John':{'age':25,'salary':20000},'Divya':{'age':35,'salary':30000}} type…why???...only
>>> for key in emp: immutable types can form the
print("Employee",key,':') keys of a dictionary.
print("Age:",emp[key]['age'])
print("Salary:",emp[key]['salary'])

Employee John :
Age: 25
Salary: 20000
Employee Divya :
Age: 35
Salary: 30000
>>>
WAP to read key(name) and age and salary of n employees in a
dictionary(nested)
=============== RESTART: C:/python37/class 11/dictionary/5.py
===============
Enter nameJohn
Enter age25
Enter salary20000
Press y to continue adding more datay
Enter nameDivya
Enter age35
Enter salary30000
Press y to continue adding more datan
{'John': {'Age’: 25, 'Salary’: 20000}, 'Divya': {'Age': 35, 'Salary': 30000}}
>>>
=============== RESTART:
WAP to read key(name) and age and salary of n C:/python37/class
employees in a dictionary(nested) 11/dictionary/5.py
===============
def create_nested_dictionary(): Enter nameJohn
emp={}
Enter age25
while True:
Enter salary20000
ag_sal={}
nm=input("Enter name") Press y to continue adding more
ag=int(input("Enter age")) datay
sl=eval(input("Enter salary")) Enter nameDivya
ag_sal['Age']=ag Enter age35
ag_sal['Salary']=sl Enter salary30000
emp[nm]=ag_sal Press y to continue adding more
ch=input("Press y to continue adding more datan
data") {'John': {'Age’: 25, 'Salary’:
if ch not in 'yY': 20000}, 'Divya': {'Age': 35,
break
'Salary': 30000}}
print(emp)
>>>
Write a menu driven program to display all the records of the dictionar

1:create
2:display all
3:search by name2
John 25 20000
Divya35 30000
1:create
2:display all
3:search by name
Write a menu driven program to display all the records of the
dictionary created in the above program.
1:create
2:display all
3:search by name2
John 25 20000
Divya35 30000
1:create
2:display all
3:search by name
def display_dict():
for name in emp:
print(name,emp[name]['Age'],emp[name]['Salary'],sep='\t')
Extend the above program to read a name of an employee, search and
display his all details. Display the error message if name is not found
{'Divya': {'Age': 25, 'Salary': 20000}, 'John': {'Age': 35, 'Salary': 30000}}
1:create
2:display all
3:search by name3
Enter name of the employee whose record is to be searchedJohn
inside if
Name John
Age 35 Salary 30000
1:create
2:display all
3:search by name3
Enter name of the employee whose record is to be searchedAakash
Aakash not found in the dictionary
Extend the above program to read a name of an employee, search and
display his all details. Display the error message if name is not found
def search_by_name():
nm=input("Enter name of the employee whose record is to be
searched")
for key in emp:
if nm==key:
print("inside if")
print("Name",nm)
print("Age",emp[nm]['Age'],"Salary",emp[nm]['Salary'],sep='\t')
break
else:
print("{} not found in the dictionary".format(nm))
Write a function update_sal(amt) to increase the salary of all the employees
by amt. Display the original and the updated dictionary

1:create
2:display all
3:search by name
4.update sal4
Enter the amount by which salary of all the employees is to be updated500
original dictionary
John 25 20000
Divya 35 30000
Records updated. Now the updated dictionary is
John 25 20500
Divya 35 30500
Write a function update_sal(amt) to increase the salary of all the employees
by amt. Display the original and the updated dictionary

def update_sal(amt):
print("original dictionary")
display_dict()
for key in emp:
emp[key]['Salary']+=amt
print("Records updated. Now the updated dictionary is")
display_dict()
Write a function update_sal_specific(name,amt) to increase the salary of
particular employee by amt. Display the original and the updated dictionary
{'John': {'Age': 25, 'Salary': 20000}, 'Divya': {'Age': 35, 'Salary': 30000}, 'Meeta': {'Age': 20,
'Salary': 25000}}
1:create
2:display all
3:search by name
4.update sal
5. update sal of specific employee5
Enter name of the employee whose sal needs to be updatedDivya
Enter amount by which sal needs to be updated1200
Records updated. Now the updated dictionary is
John 25 20000
Divya 35 31200
Meeta 20 25000
Write a function update_sal_specific(name,amt) to increase the salary of
particular employee by amt. Display the original and the updated dictionary

def update_sal_specific(name,amt):
for key in emp:
if key==name:
emp[key]['Salary']+=amt
print("Records updated. Now the updated dictionary is")
display_dict()
break
else:
print("{} not found in the dictionary".format(name))
Write a function to read a name of the employee and delete the record of that employee.
{'John': {'Age': 25, 'Salary': 20000}, 'Divya': {'Age': 35, 'Salary': 30000}, 'Reena': {'Age': 20, 'Salary': 25000}}
1:create
2:display all
3:search by name
4.update sal
5. update sal of specific employee
6.Delete an employee6
Enter name of the employee whose record needs to be deletedDivya
Employee deleted. Now the updated dictionary is
John 25 20000
Reena 20 25000
1:create
2:display all
3:search by name
4.update sal
5. update sal of specific employee
6.Delete an employee6
Enter name of the employee whose record needs to be deletedaakash
aakash not found in the dictionary
Write a function to read a name of the employee and delete the record of that employee.

def del_emp(name):
for key in emp:
if key==name:
del emp[key]
print("Employee deleted. Now the updated dictionary is")
display_dict()
break
else:
print("{} not found in the dictionary".format(name))
def create_nested_dictionary(): print("Age",emp[nm]['Age'],"Salary",emp[nm]['Salary'],sep='\t')
ag_sal={} break
while True: else:
ag_sal={} print("{} not found in the dictionary".format(nm))
nm=input("Enter name")
ag=int(input("Enter age")) def update_sal(amt):
sl=eval(input("Enter salary")) print("original dictionary")
ag_sal['Age']=ag display_dict()
ag_sal['Salary']=sl for key in emp:
emp[nm]=ag_sal emp[key]['Salary']+=amt
ch=input("Press y to continue adding more data") print("Records updated. Now the updated dictionary is")
if ch not in 'yY': display_dict()
break
print(emp)

def display_dict():
for name in emp:
print(name,emp[name]['Age'],emp[name]['Salary'],sep='\t’)

def search_by_name():
nm=input("Enter name of the employee whose record is to be
searched")
for key in emp: Complete program in two slides
if nm==key:
print("inside if")
print("Name",nm)
def update_sal_specific(name,amt): name\n4.update sal\n5. update sal of specific
for key in emp: employee\n6.Delete an employee"))
if key==name: if choice==1:
emp[key]['Salary']+=amt create_nested_dictionary()
print("Records updated. Now the updated dictionary elif choice==2:
is") display_dict()
display_dict() elif choice==3:
break search_by_name()
else: elif choice==4:
print("{} not found in the dictionary".format(name)) amt=eval(input("Enter the amount by which salary of all
the employees is to be updated"))
def del_emp(name): update_sal(amt)
for key in emp: elif choice==5:
if key==name: nm=input("Enter name of the employee whose sal needs
del emp[key] to be updated")
print("Employee deleted. Now the updated dictionary amt=eval(input("Enter amount by which sal needs to be
is") updated"))
display_dict() update_sal_specific(nm,amt)
break elif choice==6:
else: nm=input("Enter name of the employee whose record
print("{} not found in the dictionary".format(name)) needs to be deleted")
del_emp(nm)
emp={} else:
while True: break
WAP to create a dictionary d by swapping the keys and values of
dictionary d1

If
>>> dict1={1:'a',2:'b’}
Then
>>> dict2
{'a': 1, 'b': 2}
>>>
WAP to create a dictionary d by swapping the keys and values of
dictionary d1

>>> dict1={1:'a',2:'b'}
>>> dict2={}
>>> for key in dict1:
dict2[dict1[key]]=key

>>> dict2
{'a': 1, 'b': 2}
>>>
Finding the frequency of values of a dictionary

=============== RESTART: C:/python37/class 11/dictionary/6.py ===============


{60: 2, 30: 2, 50: 1, 10: 1}
now sorted data
{10: 1, 30: 2, 50: 1, 60: 2}
>>>
Finding the frequency of values of a dictionary

d={'p1':60,'p2':30,'p3':50,'p4':60,'p5':30,'p6':10}
df={}
t=tuple(d.values())
for v in t:
if v not in df:
df[v]=t.count(v)
print(df)
print("now sorted data")
print(dict(sorted(df.items())))

=============== RESTART: C:/python37/class 11/dictionary/6.py ===============


{60: 2, 30: 2, 50: 1, 10: 1}
now sorted data
{10: 1, 30: 2, 50: 1, 60: 2}
>>>
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺

You might also like