Python Dictionary – versatile data Structure

Python is really simple and powerful when you have to handle complex data objects. Dictionary is one of the popular data structures used in python. Just thought to put up quick code explaining what all you can do with a dictionary object in really simple way.


#!/usr/bin/python3
# Here is a nested dictionary object to play with
Record = { "Name": "Ramanuja",
           "Address": { "House Number": 50,
                        "Street": "Gopala Road",
                        "City": "Rama Nagar",
                        "PinCode": 909090
                      },
           "Phone": "+910090243354",
           "Mobile": "32523524545",
           "Email": "rama@nuja.com",
         }

# Original Record
print("Original Record is", Record)

# Get Name
print("Name is", Record.get('Name'))

# Get Complete Address
print("Complete Address is", Record.get('Address'))

# Get just Street from address
print(Record.get('Name'),"lives at", Record.get('Address').get('Street'))

# Update Street in Address
Record['Address']['Street'] = "Mohana Bagha Street"
print(Record.get('Name'), "Has shifted to", Record.get('Address').get('Street'))

# Add Education to record
Record['Education'] = "PostGrad"
print("And now he has completed", Record['Education'])

# Remove mobile number from record
Record.pop('Mobile')

# Here is the final complete record
print("Updated Record is", Record)

# Get Record keys
print(Record.keys())

# Get dictionary items
print(Record.items())

# Get values
print(Record.values())

Here is the output you get upon executing above code.


# Original Record
Original Record is {'Phone': '+910090243354', 'Email': 'rama@nuja.com', 'Mobile': '32523524545', 'Address': {'PinCode': 909090, 'House Number': 50, 'City': 'Rama Nagar', 'Street': 'Gopala Road'}, 'Name': 'Ramanuja'}

# Get Name
Name is Ramanuja

# Get Complete Address
Complete Address is {'PinCode': 909090, 'House Number': 50, 'City': 'Rama Nagar', 'Street': 'Gopala Road'}

# Get just Street from address
Ramanuja lives at Gopala Road

# Update Street in Address
Ramanuja Has shifted to Mohana Bagha Street

# Add Education to record
And now he has completed PostGrad

# Remove mobile number from record and show final updated record
Updated Record is {'Phone': '+910090243354', 'Education': 'PostGrad', 'Email': 'rama@nuja.com', 'Address': {'PinCode': 909090, 'House Number': 50, 'City': 'Rama Nagar', 'Street': 'Mohana Bagha Street'}, 'Name': 'Ramanuja'}

# Get Record keys
dict_keys(['Phone', 'Education', 'Email', 'Address', 'Name'])

# Get dictionary items
dict_items([('Phone', '+910090243354'), ('Education', 'PostGrad'), ('Email', 'rama@nuja.com'), ('Address', {'PinCode': 909090, 'House Number': 50, 'City': 'Rama Nagar', 'Street': 'Mohana Bagha Street'}), ('Name', 'Ramanuja')])

#Get values
dict_values(['PostGrad', '+910090243354', 'rama@nuja.com', {'House Number': 50, 'City': 'Rama Nagar', 'Street': 'Mohana Bagha Street', 'PinCode': 909090}, 'Ramanuja'])