Predictive Hacks

How to Save a Python Dictionary as a JSON file

We often need to save a Python dictionary as a JSON file. For this task, we can work with the Python built-in package called json, and more specifically with the json.dump() method. Let’s move on with an example where we will create a simple dictionary and we will save it as a json file.

import json

# create a dictionary

my_dict = { 'Name': 'George',
            'Surname': 'Pipis',
            'Country': 'Greece',
            'Company': 'Predictive Hacks',
            'Year': 2023
          }

print(my_dict)
 
{'Name': 'George', 'Surname': 'Pipis', 'Country': 'Greece', 'Company': 'Predictive Hacks', 'Year': 2023}

Now, let’s save the my_dict as a json file called my_json.json.

with open("my_json.json", "w") as fp:
    json.dump(my_dict, fp)
 

As we can see, a new file called my_json.json has been created under the working directory.

Finally, if we want to load the json file we can work as follows:

with open('my_json.json', 'r') as fp:
    data = json.load(fp)

print(data)
 
{'Name': 'George', 'Surname': 'Pipis', 'Country': 'Greece', 'Company': 'Predictive Hacks', 'Year': 2023}

Note that the data object is a dictionary.

type(data)
 
dict

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s