Turning a list of dictionaries into a list of lists

a 夏天 提交于 2020-01-30 06:30:08

问题


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'],
]

回答1:


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




回答2:


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.




回答3:


I'm not sure what ordering you want, but for no order you could do:

list_ = [list(_.values()) for _ in dict_list]



回答4:


You can use list comprehension

Python 3

>>>listdict = [ {'field1': 'a', 'field2': 'b'},
...             {'field1': 'c', 'field2': 'd'},
...             {'field1': 'e', 'field2': 'f'} ]

>>>[[a for a in dict.values()] for dict in listdict]
[['b', 'a'], ['d', 'c'], ['f', 'e']]

Python 2

>>>[dict.values() for dict in listdict]
[['b', 'a'], ['d', 'c'], ['f', 'e']]


来源:https://stackoverflow.com/questions/31627141/turning-a-list-of-dictionaries-into-a-list-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!