Nested Dictionary JSON to Nested Dictionary in Python

11,403

This is how I would write to a JSON file and read from it:

import json
from pprint import pprint

dictionary = {"Europe":
             {"France": (10,5),
              "Germany": (15,5),
              "Italy": (5,15)},

             "North-America": {
                 "USA": (20,0),
                 "CANADA": (12,4),
                 "MEXICO": (14,8)}
             }

with open("test.json", 'w') as test:
    json.dump(dictionary, test)

# Data written to test.json
with open("test.json") as test:
    dictionary = json.load(test)

pprint(dictionary)

{'Europe': {'France': [10, 5], 'Germany': [15, 5], 'Italy': [5, 15]},
 'North-America': {'CANADA': [12, 4], 'MEXICO': [14, 8], 'USA': [20, 0]}}
>>> 

# Accessing dictionary["Europe"]
print(dictionary["Europe"])

{'France': [10, 5], 'Germany': [15, 5], 'Italy': [5, 15]}
>>>

# Accessing items in dictionary["North-America"]
print(dictionary["North-America"].items())

dict_items([('USA', [20, 0]), ('CANADA', [12, 4]), ('MEXICO', [14, 8])])
>>>

Edit:

# Convert your input dictionary to a string using json.dumps()
data = json.dumps(dictionary)

# Write the string to a file
with open("test.json", 'w') as test:
    test.write(data)

# Read it back
with open("test.json") as test:
    data = test.read()

# decoding the JSON to dictionary
d = json.loads(data)

print(type(d))

<class 'dict'>
>>> 

Now you could use it like a normal dictionary:

>>> d["Europe"]
{'France': [10, 5], 'Germany': [15, 5], 'Italy': [5, 15]}
>>> d["North-America"].items()
dict_items([('USA', [20, 0]), ('CANADA', [12, 4]), ('MEXICO', [14, 8])])
>>>
Share:
11,403
CodePathLvl
Author by

CodePathLvl

Updated on June 09, 2022

Comments

  • CodePathLvl
    CodePathLvl almost 2 years

    I have a dictionary of dictionaries in Python which looks like this:

      {      
       "Europe": {
            "France": (10,5),
            "Germany": (15,5),
            "Italy": (5,15),
          },
    "North-America": {
            "USA": (20,0),
            "CANADA": (12,4),
            "MEXICO": (14,8),
           },
     }
    

    I want to save the dictionary in a JSON file to get the data when I need it. I do that store like this:

    with open(filename, 'a') as jsonfile:
        json.dump(dictionary, jsonfile)
    

    The problem comes now. When I try to read the stored json dictionary I get same Error like this: Python json.loads shows ValueError: Extra data

    The answer in that post is just to store the different dicts in a list and dumps all of them. But I dont understand how to do it if they are nested and they are created dynamically.

    The way I read the json is this:

    jsonFile = open(filename)
    data = json.loads(jsonFile)
    jsonFile.close()
    return data
    

    In resume. I need to load the dictionary from the json file to a dictionary in python. How can I achieve that?

  • CodePathLvl
    CodePathLvl over 6 years
    I see. I will try it and tell what result I have.
  • CodePathLvl
    CodePathLvl over 6 years
    Thank you so much. That was the problem, I was writing and reading without doing the encoding/decoding process.