简体   繁体   中英

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

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:

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 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']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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