从词典列表中获取词典项目

时间:2018-08-22 16:56:13

标签: python-3.x list dictionary

假设我有一本字典,然后其中有一本字典列表:

cslfJson = {'displayFieldName': 'CSLF_ID',
            'features': [{'attributes': {'OBJECTID': '13000', 'CSLF_ID': '08123', 'Area_SF': '5431'},
                         {'attributes': {'OBJECTID': '12000', 'CSLF_ID': '08137', 'Area_SF': '2111'}}]}

我如何在OBJECTID语句中调用print?我可以打印这样的东西

print(cslfJson['features'][1]['attributes']['OBJECTID'])

我正在尝试这样打印两个OBJECTID:

for index in cslfJson['features']: 
    print(cslfJson['features'][index]['attributes']['OBJECTID'])

以上内容引发了TypeError: list indices must be integers or slices, not dict错误,因此我对正确的语法感到困惑。

2 个答案:

答案 0 :(得分:2)

您要遍历列表的内容,而不是索引,因此index本身就是字典。有几种方法可以遍历索引,也可以使用给出的字典代替

for subdictionary in cslfJson['features']: 
    print(subdictionary['attributes']['OBJECTID'])

答案 1 :(得分:1)

print(*x['attributes']['OBJECTID'] for x in cslfJson['features']) 
相关问题