Dictionaries in Python
Dictionaries in Python
Dictionaries in Python
value. It is mutable (can modify its contents ) but Key must be unique and
immutable.
The data type dictionary falls under mapping. 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
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 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta’:95}
print(dict3['Mohan'])
Dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
print('neha' in dict1)
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
print('Mohan' not in dict1)
Dictionaries are mutable which implies that the contents of the dictionary can be changed after
it has been created.
A) Adding a new item
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
dict1['Meena'] = 78
print(dict1)
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
print(len(dict1))
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
print(dict1.keys())
values() Returns a list of values in the dictionary
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
print(dict1.values())
get() Returns the value corresponding to the key passed as the argument If the key is not present in the
dictionary it will return None
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
print(dict1.get('Mohan'))
clear() Deletes or clear all the items of the dictionary
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
print(dict1.clear())
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}
del dict1['Mohan']
print(dict1)
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
del dict1
print(dict1)
Consider the following dictionary state Capital:
EXAMPLE
d1={1:10,2:20,3:30}
d2={4:40,5:50}
d1.update(d2)
print (d1)
PROGRAM 22 : Write a program to enter names of employees and their
salaries as input and store them in a dictionary.
d1={1:80,2:90,3:100}
d2={4:60,7:50}
d1.update(d2)
print (d1)
PROGRAM 24 : Create a dictionary with the roll number, name and marks of n students in a class and display the names of students who have
marks above 75.
n = int(input("Enter number of students: "))
result = {}
for i in range(n):
print("Enter Details of student No.", i+1)
print(result)