Python dictionary is used to store key-value pairs data. It also called a hash map in other programming languages.
info = {
'name': 'Jone',
'last_name': 'Doe',
'email': 'jon@example.com',
'phone': '124242344'
}
print(info['name'])
print(info['email'])
print(info.get('name'))
print(info.get('email'))
print(info.get('name'))
print(info.get('country', 'Bangladesh'))
print(len(info))
info['name'] = "Mamun"
info.update( {'name': "Sarkar", 'email': 'sarkar@example.com'} )
info['city'] = "Dhaka"
info.update( {'city': "Dhaka"} )
info.pop("phone")
del info['email']
info.popitem()
del info
info.clear()
new_info = info.copy()
new_info = dict(info)
info = {
'name': 'Jone',
'last_name': 'Doe',
'email': 'jon@example.com',
'phone': '124242344',
'profile': {
'zip': 1234,
'country': "Bangladesh",
'gender': "male"
}
}
info.keys()
info.values()
info.items()
print('name' in info)
Use of items(), keys(), values() function of dictionary.
a = {'name': 'Mamun', 'nickname': 'Maateen', 'email': 'maateen@outlook.com', 'phone': '01711223344'}
print (a['name'])
a['name'] = 'Mamun Sarkar'
print (a['name'])
b = {'hometown': 'Barisal', 'fav_poet': 'Nazrul'}
a.update(b)
print (a)
del a['phone']
print (a)
b.clear()
print (b)
print ('name' in a)
print (a.items())
print (a.keys())
print (a.values())
Output:
Mamun
Mamun Sarkar
{'name': 'Mamun Sarkar', 'nickname': 'Maateen', 'email': 'maateen@outlook.com', 'phone': '01711223344', 'hometown': 'Barisal', 'fav_poet': 'Nazrul'}
{'name': 'Mamun Sarkar', 'nickname': 'Maateen', 'email': 'maateen@outlook.com', 'hometown': 'Barisal', 'fav_poet': 'Nazrul'}
{}
True
dict_items([('name', 'Mamun Sarkar'), ('nickname', 'Maateen'), ('email', 'maateen@outlook.com'), ('hometown', 'Barisal'), ('fav_poet', 'Nazrul')])
dict_keys(['name', 'nickname', 'email', 'hometown', 'fav_poet'])
dict_values(['Mamun Sarkar', 'Maateen', 'maateen@outlook.com', 'Barisal', 'Nazrul'])