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