从词典列表中提取列表

时间:2020-07-15 15:32:42

标签: python list

基本上我有这个:

my_list = [{'a': 1, 'b': 1}, {'c': 1}]

我想要这样的输出:

new_list = [['a', 'b'],['c']]

我尝试了自己的代码,但只返回了此代码:

['a', 'b', 'c'] 

2 个答案:

答案 0 :(得分:3)

这是一个可能的解决方案:

result = [list(d) for d in my_list]

它基本上等同于:

result = list(map(list, my_list))

请注意,使用list(d.keys())等同于list(d)

正如meowgoesthedog在评论中建议的那样,请谨慎使用3.7之前的Python版本:键没有排序,因此您可能最终会获得未排序的值。

答案 1 :(得分:2)

您可以轻松地做到这一点-

my_list = [{'a': 1, 'b': 1}, {'c': 1}]

res = list(map(list,my_list))

print(res)

输出:

[['a', 'b'], ['c']]

如果您不太了解上面的工作原理,可以使用一个更简单的版本来做到这一点-

my_list = [{'a': 1, 'b': 1}, {'c': 1}]

res = []
for dicts in my_list:
    res.append(list(dicts))    

# The above process is equivalent to the shorthand :
# res = [ list(dicts) for dicts in my_list ]

print(res)

输出:

[['a', 'b'], ['c']]