Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning a list of dictionaries into a list of lists

I know this is possible with list comprehension but I can't seem to figure it out. Currently I have a list of dictionaries like so:

 [ {'field1': 'a', 'field2': 'b'},
   {'field1': 'c', 'field2': 'd'},
   {'field1': 'e', 'field2': 'f'} ]

I'm trying to turn this into:

list = [
    ['b', 'a'],
    ['d', 'c'],
    ['f', 'e'],
]
like image 982
davegri Avatar asked Jan 27 '26 12:01

davegri


2 Answers

You can try:

[[x['field2'], x['field1']] for x in l]

where l is your input list. The result for your data would be:

[['b', 'a'], ['d', 'c'], ['f', 'e']]

This way you ensure that the value for field2 comes before the value for field1

like image 77
JuniorCompressor Avatar answered Jan 30 '26 01:01

JuniorCompressor


Just return the dict.values() lists in Python 2, or convert the dictionary view to a list in Python 3:

[d.values() for d in list_of_dicts]  # Python 2
[list(d.values()) for d in list_of_dicts]  # Python 3

Note that the values are not going to be in any specific order, because dictionaries are not ordered. If you expected them to be in a given order you'd have to add a sorting step.

like image 23
Martijn Pieters Avatar answered Jan 30 '26 01:01

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!