Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Convert list of dictionaries to list of lists

I want to convert a list of dictionaries to list of lists.

From this.

d = [{'B': 0.65, 'E': 0.55, 'C': 0.31},
     {'A': 0.87, 'D': 0.67, 'E': 0.41},
     {'B': 0.88, 'D': 0.72, 'E': 0.69},
     {'B': 0.84, 'E': 0.78, 'A': 0.64},
     {'A': 0.71, 'B': 0.62, 'D': 0.32}]

To

[['B', 0.65, 'E', 0.55, 'C', 0.31],
 ['A', 0.87, 'D', 0.67, 'E', 0.41],
 ['B', 0.88, 'D', 0.72, 'E', 0.69],
 ['B', 0.84, 'E', 0.78, 'A', 0.64],
 ['A', 0.71, 'B', 0.62, 'D', 0.32]]

I can acheive this output from

l=[]
for i in range(len(d)):
    temp=[]
    [temp.extend([k,v]) for k,v in d[i].items()]
    l.append(temp)

My question is:

  • Is there any better way to do this?
  • Can I do this with list comprehension?
like image 843
ResidentSleeper Avatar asked Mar 04 '23 03:03

ResidentSleeper


2 Answers

Since you are using python 3.6.7 and python dictionaries are insertion ordered in python 3.6+, you can achieve the desired result using itertools.chain:

from itertools import chain

print([list(chain.from_iterable(x.items())) for x in d])
#[['B', 0.65, 'E', 0.55, 'C', 0.31],
# ['A', 0.87, 'D', 0.67, 'E', 0.41],
# ['B', 0.88, 'D', 0.72, 'E', 0.69],
# ['B', 0.84, 'E', 0.78, 'A', 0.64],
# ['A', 0.71, 'B', 0.62, 'D', 0.32]]
like image 51
pault Avatar answered Mar 17 '23 21:03

pault


You can use a list comprehension:

result = [[i for b in c.items() for i in b] for c in d]

Output:

[['B', 0.65, 'E', 0.55, 'C', 0.31], 
 ['A', 0.87, 'D', 0.67, 'E', 0.41], 
 ['B', 0.88, 'D', 0.72, 'E', 0.69], 
 ['B', 0.84, 'E', 0.78, 'A', 0.64], 
 ['A', 0.71, 'B', 0.62, 'D', 0.32]]
like image 45
Ajax1234 Avatar answered Mar 17 '23 19:03

Ajax1234