Reputation: 675
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
Upvotes: 1
Views: 55
Reputation: 164623
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'])
Upvotes: 2
Reputation: 82765
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']]
Upvotes: 0