繁体   English   中英

从字典列表中提取列表

[英]Extract lists from a list of dictionaries

基本上我有这个:

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

我想要一个像这样的 output :

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

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

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

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

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

它基本上相当于:

result = list(map(list, my_list))

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

正如 meowgoesthedog 在评论中所建议的那样,请注意 Python 版本早于 3.7:键未排序,因此您最终可能会得到未排序的值。

你可以很容易地做到这一点 -

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

res = list(map(list,my_list))

print(res)

OUTPUT:

[['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)

OUTPUT:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM