Dictionary in Python : Element Lookup

Dictionary

Dictionary is useful for element lookup, Its key value pair. Each key must have value. It is useful to store key value pair in program.

Following Python program demonstrate an example for:

  1. Initialize
  2. Add
  3. Update
  4. Access Element
  5. Iterate
  6. Delete element
  7. Dict to JSON String
  8. JSON to Dict
import json

#initialize
product = {'name':'Nexus 5','price':800.0,'camera':'13 MP'}

#print
print("Name:" + product['name'])

#iterate
for key in product:
 print(key +" : "+str(product[key]))

#add
product['bluetooth']='Bluetooth 4.0'
print(product)

#update
product['price']=900.0
print(product['price'])

#delete
del product['camera'];
print(product)

#convert to json string
print(json.dumps(product))

#clear all
product.clear()
print(product)

#delete
del product

#json string to dictionary
json_str = '{"name":"Nexus 5","price":800.0,"camera":"13 MP"}'
product = json.loads(json_str) 
print(product['name'])

Output

#print
Name:Nexus 5

#iterate
name : Nexus 5
camera : 13 MP
price : 800.0

#add
{'name': 'Nexus 5', 'bluetooth': 'Bluetooth 4.0', 'camera': '13 MP', 'price': 800.0}

#update
900.0

#delete
{'name': 'Nexus 5', 'bluetooth': 'Bluetooth 4.0', 'price': 900.0}

#To JSON String
{"name": "Nexus 5", "bluetooth": "Bluetooth 4.0", "price": 900.0}

#After Clear
{}

#After JSON String to Dictionary
Nexus 5

For More Help Refer Official Documentation of Python Dictionaries.

Leave a Reply

Your email address will not be published. Required fields are marked *