Use of python dictionary

Author: Al-mamun Sarkar Date: 2020-03-24 20:39:52

Python dictionary is used to store key-value pairs data. It also called a hash map in other programming languages. 

 

Create a Dictionary:

info = {
    'name': 'Jone', 
    'last_name': 'Doe', 
    'email': 'jon@example.com', 
    'phone': '124242344'
}

 

Access item of a dictionary:

print(info['name'])
print(info['email'])

 Access item of a dictionary using get() method:

print(info.get('name'))
print(info.get('email'))

 Set a value if a key doesn't exist in the dictionary:

print(info.get('name'))
print(info.get('country', 'Bangladesh'))

 

 Getting the length of a dictionary:

print(len(info))

 

Change value:

info['name'] = "Mamun"

Change value using update() method:

info.update( {'name': "Sarkar", 'email': 'sarkar@example.com'} )

 

Add a new item to the dictionary:

info['city'] = "Dhaka"

 Add new item using update() method:

info.update( {'city': "Dhaka"} )

 

 

Deleting Items:

info.pop("phone")
del info['email']

Deleting last Items:

info.popitem()

 Deleting the dictionary:

del info

  Make the dictionary empty:

info.clear()

 

Copy a dictionary:

new_info = info.copy()
new_info = dict(info)

 

Create Nested Dictionary:

info = {
    'name': 'Jone', 
    'last_name': 'Doe', 
    'email': 'jon@example.com', 
    'phone': '124242344',
    'profile': {
        'zip': 1234,
        'country': "Bangladesh",
        'gender': "male"
    }
}

 

Get all keys of the dictionary:

info.keys()

 Get all values of the dictionary:

info.values()

 Get a tuple of key and value of all items of the dictionary:

info.items()

 

Check if Key Exists in dictionary:

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'])