4

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?

4
  • 2
    Why are you appending to your file? Use the w mode, JSON is not a streamable format by itself. Commented Dec 17, 2017 at 19:50
  • My bad. I dont know why I wrote 'a' mode when actually is 'w' mode Commented Dec 17, 2017 at 19:59
  • the loading method is like this: jsonFile = open(filename) data = json.loads(jsonFile) jsonFile.close() return data Commented Dec 17, 2017 at 20:07
  • 1
    Use json.load() if you want to load from a file object. json.loads() is only for parsing already loaded strings. Commented Dec 17, 2017 at 20:17

1 Answer 1

7

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])])
>>>
Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.