[英]convert a list of dictionaries to a dictionary with dict comprehension
Original: 原版的:
# abs is not a string, it's a function name
[{'name': 'abs'}, {'op': abs}]
to 至
{'name': 'abs', 'op': abs}
My code: 我的代码:
op = [{'name': 'abs'}, {'op': abs}] # key value is unique
new_dict = {}
for item in op:
new_dict.update(item)
Is there a way to do the same with dict comprehension? 有没有办法对dict理解做同样的事情?
Code: 码:
list_of_dicts = [{'name': 'abs'}, {'op': abs}]
new_dict = {k: v for element in list_of_dicts for k, v in element.items()}
Output: 输出:
{'name': 'abs', 'op': <built-in function abs>}
Using dict
使用
dict
Ex: 例如:
data = [{'name': 'abs'}, {'op': abs}]
print(dict(tuple(*i.items()) for i in data))
Output: 输出:
{'name': 'abs', 'op': <built-in function abs>}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.