4

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?
ResidentSleeper
  • 2,385
  • 2
  • 10
  • 20

3 Answers3

3

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]]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • 2
    This seems what the OP is asking for, just a note that the order of `items()` is not deterministic and may change depending on the data and the run. – jdehesa Apr 17 '19 at 16:10
3

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]]
pault
  • 41,343
  • 15
  • 107
  • 149
  • Thanks for response and note. So if I use python version < 3.7, I have to use `chain` to make sure it arrange in order? – ResidentSleeper Apr 17 '19 at 16:23
  • 1
    No, below 3.6 dictionaries are not guaranteed to maintain order. You'd have to use an [`OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict) in older versions. `chain` here is just used to [flatten the tuples](https://stackoverflow.com/a/953097/5858851) returned by `items` – pault Apr 17 '19 at 16:28
1

using lambda this can be done as

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}]

d1=list(map(lambda x: [j for i in x.items() for j in i], d))
print(d1)
"""
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]]

"""
sahasrara62
  • 10,069
  • 3
  • 29
  • 44