SlyCooper
SlyCooper

Reputation: 21

Iterating through and adding multiple Json files to a dictionary

So my question is this. I have these JSON files stored in a list called json_list

['9.json',
 '8.json',
 '7.json',
 '6.json',
 '5.json',
 '4.json',
 '3.json',
 '2.json',
 '10.json',
 '1.json',]

Each of these files contains a dictionary with an (ID NUMBER: Rating).

This is my code below. The idea is to store all of the keys and values of these files into a dictionary so it will be easier to search through. I've separated the keys and values so it will be easier to add into the dictionary. The PROBLEM is that this iteration only goes through the file '1.json' and then stops. I'm not sure why its not going through all 10.

for i in range(len(json_list)):
    f = open(os.path.join("data", json_list[i]), encoding = 'utf-8')
    file = f.read()
    f.close()
    data = json.loads(file)
    keys = data.keys()
    values = data.values()

Upvotes: 1

Views: 1276

Answers (1)

Thaer A
Thaer A

Reputation: 2323

Here:

data = json.loads(file)
keys = data.keys()
values = data.values()

You're resetting the value for keys and values instead of appending to it.

Maybe try appending them, something like (The dictionary keys MUST be unique in each file or else you'll be overwriting data):

data = json.loads(file)
keys += list(data.keys())
values += list(data.values())

Or better yet just append the dictionary (The dictionary keys MUST be unique in each file or else you'll be overwriting data):

all_data = {}
for i in range(len(json_list)):
    f = open(os.path.join("data", json_list[i]), encoding = 'utf-8')
    file = f.read()
    f.close()
    data = json.loads(file)
    all_data = {**all_data, **data}

Working example:

import json
ds = ['{"1":"a","2":"b","3":"c"}','{"aa":"11","bb":"22","cc":"33", "dd":"44"}','{"foo":"bar","eggs":"spam","xxx":"yyy"}']
all_data = {}
for d in ds:
    data = json.loads(d)
    all_data = {**all_data, **data}

print (all_data)

Output:

{'1': 'a', '2': 'b', '3': 'c', 'aa': '11', 'bb': '22', 'cc': '33', 'dd': '44', 'foo': 'bar', 'eggs': 'spam', 'xxx': 'yyy'}

If the keys are not unique try appending the dictionaries to a list of dictionaries like this:

import json
ds = ['{"1":"a","2":"b","3":"c"}','{"aa":"11","bb":"22","cc":"33", "dd":"44"}','{"dd":"bar","eggs":"spam","xxx":"yyy"}']
all_dicts= []
for d in ds:
    data = json.loads(d)
    all_dicts.append(data)

print (all_dicts)
# to access key
print (all_dicts[0]["1"])

Output:

[{'1': 'a', '2': 'b', '3': 'c'}, {'aa': '11', 'bb': '22', 'cc': '33', 'dd': '44'}, {'dd': 'bar', 'eggs': 'spam', 'xxx': 'yyy'}]
a

Upvotes: 1

Related Questions