猿问

访问 Python 列表中的字典

我有一个列表,其中包含这样的字典:


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

我希望它存储在这样的列表列表中:


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

为了从我尝试过的字典中读取 id


for d in json_obj:

    print(d['id'])

但是我在上面的代码中看到了这个错误:


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


繁星coding
浏览 232回答 2
2回答

心有法竹

您有一个嵌套的列表列表。有时有助于明显地观察这一点,注意嵌套[]语法:json_obj = [[{'id': None}, {'id': 'abc'}, {'id': 'def'}, {'id': 'ghi'}],            [{'id': None}, {'id': 'jkl'}, {'id': 'mno'}, {'id': 'pqr'}]]您的语法适用于单个列表: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'])对于嵌套列表,您可以使用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 chainfor d in chain.from_iterable(json_obj):    print(d['id'])或者,如果没有导入,您可以使用嵌套for循环:for L in json_obj:    for d in L:        print(d['id'])

慕后森

使用嵌套列表理解。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] )或者for i in json_obj:    for j in i:        print(j["id"])输出:[[None, '5b98d01c0835f23f538cdcab', '5b98d0440835f23f538cdcad', '5b98d0ce0835f23f538cdcb9'], [None, '5b98d01c0835f23f538cd', '5b98d0440835f23f538cd', '5b98d0ce0835f23f538cdc']]
随时随地看视频慕课网APP

相关分类

Python
我要回答