Dictionary - Notes Python Ncert
Dictionary - Notes Python Ncert
Creating a Dictionary
The words entered are contained in curly brackets and are separated by
commas to form a dictionary. Each item is a pair of key values that are
separated by colons (:). The dictionary’s keys must be distinct and of any
immutable data type, such as an integer, text, or tuple. The values may be of
any data type and may be repeated.
Example –
>>> dict3 = {‘Mohan’:95,’Ram’:89,’Suhel’:92,’Sangeeta’:85}
>>> dict3
{‘Mohan’: 95, ‘Ram’: 89, ‘Suhel’: 92,’Sangeeta’: 85}
We can add a new item to the dictionary as shown in the following example –
Example –
>>> dict1 = {‘Mohan’:95,’Ram’:89,’Suhel’:92,’Sangeeta’:85}
>>> dict1[‘Meena’] = 78
>>> dict1
{‘Mohan’: 95, ‘Ram’: 89, ‘Suhel’: 92,’Sangeeta’: 85, ‘Meena’: 78}
Example –
>>> dict1 = {‘Mohan’:95,’Ram’:89,’Suhel’:92,’Sangeeta’:85}
>>> dict1[‘Suhel’] = 93.5
>>> dict1
{‘Mohan’: 95, ‘Ram’: 89, ‘Suhel’: 93.5,’Sangeeta’: 85}
Dictionary Operations
Membership
The membership operator in checks if the key is present in the dictionary and
returns True, else it returns False.
Example –
>>> 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.
Example –
>>> 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.
METHOD 1
>>> dict1 ={‘Mohan’:95,’Ram’:89,’Suhel’:92,’Sangeeta’:85}
>>> for key in dict1:
print(key,’:’,dict1[key])
Output –
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Method 2
>>> for key,value in dict1.items():
print(key,':',value)
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
len() - Returns the length or number of key: value pairs of the dictionary
passed as the argument.
Example –
>>> dict1 = {‘Mohan’:95,’Ram’:89,
‘Suhel’:92, ‘Sangeeta’:85}
>>> len(dict1)
4
del() - Deletes the item with the given key To delete the dictionary from the
memory we write: del Dict_name
Example –
>>> dict1 = {‘Mohan’:95,’Ram’:89,’Suhel’:92, ‘Sangeeta’:85}
>>> del dict1[‘Ram’]
>>> dict1
{‘Mohan’:95,’Suhel’:92, ‘Sangeeta’: 85}
>>> del dict1 [‘Mohan’]
>>> dict1
{‘Suhel’: 92, ‘Sangeeta’: 85}