3

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?

Dan Loewenherz
  • 10,879
  • 7
  • 50
  • 81
CodePathLvl
  • 77
  • 1
  • 2
  • 6
  • 2
    Why are you appending to your file? Use the `w` mode, JSON is not a streamable format by itself. – zwer Dec 17 '17 at 19:50
  • My bad. I dont know why I wrote 'a' mode when actually is 'w' mode – CodePathLvl Dec 17 '17 at 19:59
  • the loading method is like this: jsonFile = open(filename) data = json.loads(jsonFile) jsonFile.close() return data – CodePathLvl Dec 17 '17 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. – zwer Dec 17 '17 at 20:17

1 Answers1

6

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])])
>>>
srikavineehari
  • 2,502
  • 1
  • 11
  • 21