简体   繁体   中英

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?

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

Ex:

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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