Home > Mobile >  Accessing values in nested dictionaries within multiple files?
Accessing values in nested dictionaries within multiple files?

Time:05-19

I have a folder with twenty .png file and a .json file each. The .json file looks like below

{
"ID":12,
"flags"={},
"shapes":[
{"label":"text",
"points":[[65, 14],[27, 40]],
}
],
"flags"={},
"shapes":[
{"label":"logo",
"points":[[165, 124],[207, 43]],
}
],
"flags"={},
"shapes":[
{"label":"text",
"points":[[54, 24],[17, 53]],
}
]
}

I want to make a list of all the "label"s in each file. How can I do this?

I tried

import os
import json

path_to_json = './'
contents=[]

for file_name in [file for file in os.listdir(path_to_json) if file.endswith('.json')]:
    with open(path_to_json   file_name) as json_file:
        data=json.load(json_file)
        contents.append(data)

it looks fine till here, now I need to fetch the value for "label" and the following part doesn't work

l=[]
for i in range(len(contents)):
    label= contents[i]['shapes']['label']
    l.append(label)
print(l)

CodePudding user response:

shapes is a list, so you'll have to iterate over it:

l = []
for content in contents:
    for shape in content['shapes']:
        l.append(shape['label'])
print(l)
  • Related