简体   繁体   English

在Python列表中访问字典

[英]Accessing dictionary inside Python List

I have a list which contains dictionaries like this: 我有一个包含这样的字典的列表:

json_obj = [[{'id': None},{'id': '5b98d01c0835f23f538cdcab'},{'id': '5b98d0440835f23f538cdcad'},{'id': '5b98d0ce0835f23f538cdcb9'}],[{'id': None},{'id': '5b98d01c0835f23f538cd'},{'id': '5b98d0440835f23f538cd'},{'id': '5b98d0ce0835f23f538cdc'}]]

I want it to store in list of lists like this: 我希望它存储在这样的列表列表中:

y=[['None','5b98d01c0835f23f538cdcab','5b98d0440835f23f538cdcad','5b98d0ce0835f23f538cdcb9'],['None','5b98d01c0835f23f538cd','5b98d0440835f23f538cd','5b98d0ce0835f23f538cdc']]

For reading the id from the dictionary I tried 为了从字典中读取ID,我尝试了

for d in json_obj:
    print(d['id'])

But I see this error with the above code: 但是我在上面的代码中看到了这个错误:

TypeError: list indices must be integers or slices, not str

You have a nested list of lists . 您有一个嵌套的列表列表 It sometimes helps to observe this visibly, note the nested [] syntax: 有时可以明显观察到这一点,请注意嵌套的[]语法:

json_obj = [[{'id': None}, {'id': 'abc'}, {'id': 'def'}, {'id': 'ghi'}],
            [{'id': None}, {'id': 'jkl'}, {'id': 'mno'}, {'id': 'pqr'}]]

Your syntax would works for single list: 您的语法适用于单个列表:

json_obj = [{'id': None}, {'id': 'abc'}, {'id': 'def'}, {'id': 'ghi'},
            {'id': None}, {'id': 'jkl'}, {'id': 'mno'}, {'id': 'pqr'}]

for d in json_obj:
    print(d['id'])

For nested lists, you can use itertools.chain.from_iterable from the standard library: 对于嵌套列表,可以使用标准库中的itertools.chain.from_iterable

json_obj = [[{'id': None}, {'id': 'abc'}, {'id': 'def'}, {'id': 'ghi'}],
            [{'id': None}, {'id': 'jkl'}, {'id': 'mno'}, {'id': 'pqr'}]]

from itertools import chain

for d in chain.from_iterable(json_obj):
    print(d['id'])

Or, without an import you can use a nested for loop: 或者,如果没有导入,则可以使用嵌套的for循环:

for L in json_obj:
    for d in L:
        print(d['id'])

Using a nested list comprehension. 使用嵌套列表理解。

json_obj = [[{'id': None},{'id': '5b98d01c0835f23f538cdcab'},{'id': '5b98d0440835f23f538cdcad'},{'id': '5b98d0ce0835f23f538cdcb9'}],[{'id': None},{'id': '5b98d01c0835f23f538cd'},{'id': '5b98d0440835f23f538cd'},{'id': '5b98d0ce0835f23f538cdc'}]]
print( [[j["id"] for j in i] for i in json_obj] )

or 要么

for i in json_obj:
    for j in i:
        print(j["id"])

Output: 输出:

[[None, '5b98d01c0835f23f538cdcab', '5b98d0440835f23f538cdcad', '5b98d0ce0835f23f538cdcb9'], [None, '5b98d01c0835f23f538cd', '5b98d0440835f23f538cd', '5b98d0ce0835f23f538cdc']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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