复杂的Python字典项检索/打印

时间:2015-09-22 19:57:22

标签: python json parsing dictionary

我发现自己在python词典(json)地狱。请参阅我在下面模拟的json代码,它模仿我的真实数据片段。我了解如何使用Python通过Key1e获取与Key2ejsondata['Dict1]['Dict1a']['Key2'][0]['Key1a'][0]['Key1b']['Key12c']相关联的值。但现在我想在每次出现时打印这些值。 编辑我正在使用json模块。

编辑:我试过了:

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

...然后我想迭代其中的15个项目进行打印,所以我尝试了:

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

我也尝试过:

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

......无济于事(当然是同样的错误)

但是上面产生的“列表索引必须是整数,而不是str”错误。我应该尝试获取索引值吗?

我还包含了将代码粘贴到在线JSON查看器时显示的JSON结构的屏幕截图。

{"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}}}]}]}}}

其他修改:请注意0下的Key1a是指15中的一个,但未在下面的JSON视图中显示。这是我想要迭代的15个项目。

This is the JSON structure (I pasted the above code into an online json viewer)

1 个答案:

答案 0 :(得分:0)

解决了它。因为循环不正确。 应该是:

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