In today’s Python automation tutorial we’ll learn how we can quite easily export the contents of a Python dictionary into standalone files that you are able to store for further processing. Specifically we will look into saving dictionaries into json (JavaScript object notation) files which you can store online or on your workstation / server.
Creating a simple dictionary
To get us started, we’ll create a very simple example dictionary. You can use it to follow along this tutorial.
# creating a simple dictionary object
month = ['April', 'January', 'May', 'May', 'May']
area = ['Python', 'R', 'Java', 'Javascript', 'Python']
city = ['LA', 'Quebec', 'Paris', 'Paris', 'London']
salary = [167.0, 162.0, 174.0, 162.0, 162.0]
hr_data = dict(area=area, city=city, salary = salary)
Save Python dictionaries to json files
Python delivers the json library, which makes it very easy to interact with json files.
import json
#define the path for your json file
j_path = 'C:\\temp\\hr_data.json'
# open your json file and add the dictionary
with open (j_path, 'w') as j:
json.dump(hr_data, j)
Reading json files with Python
If we want to read back our json file into a dictionary in your Python program, you can do that as following:
# define a dictionary
hr_data_read_j ={}
# load the file contents into the dictionary
with open (j_path,'rb') as j:
hr_data_read_j.update(json.load(j))
Add to json files with Pandas
If you are a Data Analyst and already working with the third party Pandas library, you can use it to deal with interact with json files.
For example, if you would like to write a dictionary into a json, you can convert it into a DataFrame and export it to an external json file using a couple lines of code:
# import pandas
import pandas as pd
#convert your dictionary to a DataFrame
hr_df = pd.DataFrame(hr_data)
j_path = 'C:\\temp\\hr_data_p.json'
#export the DataFrame to json
hr_df.to_json(path_or_buf = j_path)
Note: don’t forget to pip install and import the pandas library into your dev environment before using it. Here’s how to troubleshoot pandas install issues you might encounter.
Reading the json file contents is also a breeze:
hr_df_p = pd.read_json(j_path)
hr_df_p.head()