Pacific-Design.com

    
Home Index

1. Python

2. JSON

Python / JSON /

Read and Write Dictionary to and from JSON

#!/usr/bin/python
import json
#-------------------------------------------------#
dict =  { 
            1 : "Los Angeles",
            2 : "Agoura Hills",
            3 : "Calabasas",
            4 : "Malibu",
            5 : "Santa Monica" 
        }   

#-------------------------------------------------#
#           Write to JSON 
#-------------------------------------------------#
print("--- Write Dictionary to JSON ---")
print(dict)        
with open('cities.json', 'w') as file:
    json.dump(dict, file)
 

#-------------------------------------------------#
#           Read from JSON 
#-------------------------------------------------#
print("\n--- Read Dictionary from JSON ---")
new_dict={}
with open('cities.json') as file:
    new_dict = json.load(file)

print(new_dict)    

#-------------------------------------------------#


Output

--- Write Dictionary to JSON --- {1: 'Los Angeles', 2: 'Agoura Hills', 3: 'Calabasas', 4: 'Malibu', 5: 'Santa Monica'} --- Read Dictionary from JSON --- {u'1': u'Los Angeles', u'3': u'Calabasas', u'2': u'Agoura Hills', u'5': u'Santa Monica', u'4': u'Malibu'}