Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list of dictionaries into list of lists

Tags:

python

I have a list of dicts and i want to make separate list of each key in dicts. The keys of the dicts are the same. This is an example below:

convert this:

myList = [{'a':0,'b':2},{'a':1,'b':3}]

to:

newList = [[0,1],[2,3]]
like image 923
MOHRE Avatar asked Dec 15 '15 07:12

MOHRE


People also ask

How do you convert a dictionary into a list?

To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.


2 Answers

You can use dict.values() within a list comprehension to get the values and then use zip in order to get the columns :

>>> zip(*[d.values() for d in myList])
[(0, 1), (2, 3)]

If you want list of list :

>>> [list(col) for col in zip(*[d.values() for d in myList])]
[[0, 1], [2, 3]]
like image 72
Mazdak Avatar answered Nov 15 '22 03:11

Mazdak


I find this site that use blew code: How to convert a list of dictionaries to a list of lists in Python

[[row[key] for row in myList] for key in keylist]

Test:

def bycol_decl(lod, keylist):
    return  [[row[key] for row in lod] for key in keylist]

if __name__ == "__main__": 
    lod = [
        {'a':1, 'b':2, 'c':3},
        {'a':4, 'b':5, 'c':6},
        {'a':7, 'b':8, 'c':9},
        ]
    keylist = ['a', 'b', 'c']
    print bycol_decl(lod, keylist)

Results:

[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
like image 29
MOHRE Avatar answered Nov 15 '22 03:11

MOHRE