Dictionaries hold key-value pairs which are known as items.
SYNTAX :
dictionary_name = { key_1 : value_1, key_N : value_N}
Empty dictionary
dictionary_name = {}
To access items from the dictionary
dictionary_name[ key ]
Example :
Students = {'Akshat' : 100 , 'Raju' :80 , 'Naresh':90}
Akshat_score = Students['Akshat']
print('Score of akshat is {}'.format(Akshat_score))
OUTPUT : Score of akshat is 100
To Replace a value in Dictionary
Students = {'Akshat' : 100 , 'Raju' :80 , 'Naresh':90}
Students['Akshat'] = 99
Akshat_score = Students['Akshat']
print('Score of akshat is {}'.format(Akshat_score))
OUTPUT : Score of akshat is 99
Add new item in dictionary
Students = {'Akshat' : 100 , 'Raju' :80 , 'Naresh':90}
Students['Pareek'] = 80
print(Students)
OUTPUT : {'Pareek': 80, 'Akshat': 100, 'Naresh': 90, 'Raju': 80}
Remove items from dictionary: use del keyword
Students = {'Akshat' : 100 , 'Raju' :80 , 'Naresh':90}
del Students['Raju']
print(Students)
OUTPUT : {'Naresh': 90, 'Akshat': 100}
Accessing multiple values for a single value using for loop
Students = {'Akshat' : [100 ,89,90], 'Raju' :80 , 'Naresh':90}
for num in Students['Akshat'] :
print('Marks are {}'.format(num))
OUTPUT :
Marks are 100
Marks are 89
Marks are 90
How to use keys() and values() functions ? Check below example
Students = {'Akshat' : [100 ,89,90], 'Raju' :80 , 'Naresh':90}
if 'Akshat' in Students.keys() :
print(Students['Akshat'][0])
else:
print('not found')
OUTPUT : 100
Students = {'Akshat' : [100,89,90], 'Raju' :80 , 'Naresh':90}
print (80 in Students.values())
OUTPUT : True
Looping in Dictionaries
website = {
'Technoname':'Best website',
'DevelopedBy' : 'Akshat Jain'
}
for num in website :
print('{0} {1}'.format(num, website[num]))
OUTPUT :
Technoname Best website
DevelopedBy Akshat Jain