簡體   English   中英

使用dict理解將字典列表轉換為字典

[英]convert a list of dictionaries to a dictionary with dict comprehension

原版的:

# abs is not a string, it's a function name 
[{'name': 'abs'}, {'op': abs}]

{'name': 'abs', 'op': abs}

我的代碼:

op = [{'name': 'abs'}, {'op': abs}] # key value is unique 
new_dict = {}
for item in op:
    new_dict.update(item)

有沒有辦法對dict理解做同樣的事情?

碼:

list_of_dicts = [{'name': 'abs'}, {'op': abs}]
new_dict = {k: v for element in list_of_dicts for k, v in element.items()}

輸出:

{'name': 'abs', 'op': <built-in function abs>}

使用dict

例如:

data = [{'name': 'abs'}, {'op': abs}]
print(dict(tuple(*i.items()) for i in data))

輸出:

{'name': 'abs', 'op': <built-in function abs>}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM