简体   繁体   中英

Complex Python dictionary item retrieval/ printing

I find myself in python dictionary (json) hell. Please see the json code I mocked-up below that mimics a snip of my real data. I understand how to use Python to get the values associated with the Key1e and Key2e via jsondata['Dict1]['Dict1a']['Key2'][0]['Key1a'][0]['Key1b']['Key12c'] . But now I want to print these values every time they appear. Edit I'm using the json module.

Edit: I've tried:

activity = jsondata['Dict1']['Dict1a']['Key2'][0]['Key1a']

...then I want to iterate over the 15 items within it to print, so I tried:

for i in activity:
    print ['Key1b']['Key12c'] #to actually retrieve what's in `Key12c`

I also tried:

holder = []
for i in activity:
    holder.append(['Key1b']['Key12c'])

...to no avail (same error of course)

But the above produces a "list indices must be integers, not str" error. Should I be attempting to get the index values?

I also included a screenshot of the JSON structure revealed when I pasted my code into an online JSON viewer.

{"Dict1":{"Dict1a":{"Key1":"Value1","Key2":[{"Key1a":[{"Key1b":
{"Key1c":"Value1c","Key2c":"Value2c","Key3c":{"Key1d":"Value1d","Key2d":"Value2d"},
"Key4c":"Value4c","Key5c":"Value5c","Key6c":"Value6c","Key7c":"Value7c",
"Key8c":"Value8c","Key9c":"Value9c","Key10c":[],"Key11c":"Value11c",
"Key12c":{"Key1e": 1234,"Key2e": 5378}}}]}]}}}

Another edit: Please note that the 0 under the Key1a refers to one of 15, but that's not represented in the JSON view below. It's these 15 items I'd like to iterate over.

这是JSON结构(我将上面的代码粘贴到了在线json查看器中)

Solved it. For loop was incorrect. Should have been:

for i in activity:
   print i['Key1b']['Key12c']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM