簡體   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