我有一个包含这样的字典的列表:
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
答案 0 :(得分: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 chain
for d in chain.from_iterable(json_obj):
print(d['id'])
或者,如果没有导入,则可以使用嵌套的for
循环:
for L in json_obj:
for d in L:
print(d['id'])
答案 1 :(得分:0)
使用嵌套列表理解。
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']]