Skip to content
Advertisement

List of list of dicts values to list in python

The order of the resulted list is irrelevant, I need to add the elements afterwards.

Input1: [[{'a': 57}], 87] 
Expect Output1: [57,87]

Input2: [[{'a': 57, 'b':12}], 87] 
Expect Output2: [57,12,87]

Input3: [[{'a': 57}], 12, [{'a':34}], 87] 
Expect Output3: [57,12,34,87]

Advertisement

Answer

That’s Pretty Simple all you Need is to just check the Type of the object

Then If it’s a list get the first index of it which is a dict

So for example if i have [{1,2,3}] It will convert it to Just {1,2,3}

Then Looping Through The values(not the keys) in the Dict and just adds it to a list

Whereas If it’s not a list then just add it to the list

Input3 = [[{'a': 57}], 12, [{'a':34}], 87] 

li = []

for i in Input3: 
    if type(i) == list:
        for item in i[0].values():
            li.append(item)
        
    else:
        li.append(i)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement