0

I am trying to store a specific JSON file that resides in each subfolder in a root folder.

I managed to do that and now I have this list:

list_1

which gives:

['C:\\Users\\user\\Downloads\\problem00001\\ground-truth.json',
 'C:\\Users\\user\\Downloads\\problem00002\\ground-truth.json',
 'C:\\Users\\user\\Downloads\\problem00003\\ground-truth.json']

Now I am trying to open each of these JSON files inside a list but only the last one is stored. The goal is to store all of them together instead of only the last.

Here is what I tried:

for k in list_1:
    with open(k, 'r') as f:
        gt = {}
        gt2=[]
        for i in json.load(f)['ground_truth']:
            #print(i) <--- This here prints exactly what I need
            gt[i['unknown-text']] = i['true-author']
        gt2.append(gt)    

I guess in each iteration it gets replaced but not sure.

2 Answers 2

2

You reinitialize gt2 list at every for loop. Therefore it should be outside of the loop.

gt2=[]
for k in list_1:
    with open(k, 'r') as f:
        gt = {}
        for i in json.load(f)['ground_truth']:
            #print(i) <--- This here prints exactly what I need
            gt[i['unknown-text']] = i['true-author']
        gt2.append(gt)   
Sign up to request clarification or add additional context in comments.

2 Comments

Do you think the gt = {} is not necessary?
I don't know the use-case but it looks like it is not necessary. You can directly use gt2.append(i['true-author']) just after the print(i) line, but i think you want some uniqueness.
0

You are overwriting the local gt2=[] varible each and every time after reading the file. You sould define that before iterating the loop over list_1 as:

gt2 =[]
for k in list_1:
    with open(k, 'r') as f:
        gt = {}
        for i in json.load(f)['ground_truth']:
            #print(i) <--- This here prints exactly what I need
            gt[i['unknown-text']] = i['true-author']
        gt2.append(gt)

Comments

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.