简体   繁体   中英

Pythonic way to transform list of pairs to dict

I have a List of pairs like this:

[
    {'Name': 'first_name', 'Value': 'Joe'},
    {'Name': 'last_name', 'Value': 'Smith'},
    {'Name': 'gender', 'Value': 'male'}
]

I want to transform it into a Dict like this:

{
    'first_name': 'Joe',
    'last_name': 'Smith',
    'gender': 'male'
}

I am currently using a simple loop to accomplish this now but I know there is a more Pythonic way to do it. Thoughts?

-Tony

It was easier than I expected:

{pair['Name']:pair['Value'] for pair in source_list}

This uses a feature of Python called a Dict comprehension.

您可以在列表中的每个字典上使用values()方法的生成器输出实例化字典:

dict(d.values() for d in l)

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