原始:
# 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理解做同样的事情?
答案 0 :(得分:2)
代码:
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>}
答案 1 :(得分:1)
使用dict
例如:
data = [{'name': 'abs'}, {'op': abs}]
print(dict(tuple(*i.items()) for i in data))
输出:
{'name': 'abs', 'op': <built-in function abs>}