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:
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]]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With