从字典列表中提取列表

3

基本上,我有这个:

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

我希望您能够输出以下内容:

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

我尝试了自己的代码,但它只是返回这个:
['a', 'b', 'c'] 

1
请发布您自己的代码,并指定您的Python版本(在3.7之前,字典是无序的)。 - meowgoesthedog
1
list(map(list, my_list)) - Yevhen Kuzmovych
2个回答

3

以下是一种可能的解决方案:

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

这基本上等同于:

result = list(map(list, my_list))

注意使用list(d.keys())list(d)是等价的。

正如评论中meowgoesthedog所建议的,对于Python版本低于3.7的情况要小心:键是无序的,因此您可能最终得到未排序的值。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接