I have a list of objects and would like to transform it into a list of lists of objects. That sounds like the start of tongue twister so it may be easier to demonstrate visually:
initial_list = [
{"text": "Ham Skins", "id": "A1"},
{"text": "Pig Feet", "id": "A2"}
]
list_of_lists = [
[{"text": "Ham Skins", "id": "A1"}],
[{"text": "Pig Feet", "id": "A2"}]
]
This is very straightforward with list comprehensions:
list_of_lists = [[obj] for obj in initial_list]
At a later stage I want to work with this strange list of lists and flatten it back out again to create a single list of id codes. I assumed list comprehensions would come to my rescue again, which they utimately did but not before giving me a syntactical headache.
Starting with a more complex list_of_lists:
[
[
{"text": "Ham Skins", "id": "A1"},
{"text": "Hog Liver", "id": "A4"}
],
[
{"text": "Pig Feet", "id": "A2"}
]
]
It’s worth noting that my actual list of lists may contain multiple objects, not just one object per list as shown initially.
my desired endpoint is:
["A1", "A4", "A2"]
My initial attempt with list comprehensions was a fail.
attempted_id_lists = [obj['id'] for obj in list for list in list_of_lists]
This gives me a TypeError: 'type' object is not iterable
The syntax trick is to work back from a loop. So if I was writing my challenge as a loop, it would look like this:
for list in list_of_lists:
for obj in list:
obj['id']
To construct nested list comprehensions, move obj['id']
to the start and then join the loop statements.
successful_id_lists = [obj['id'] for list in list_of_lists for obj in list]
Thanks to Serafeim Papastefanos for showing the light and some more complex examples!
Comments