简体   繁体   中英

Pythonic Name-Value pairs to Dictionary Conversion

Given an array of dicts of name–value pairs, what is the most effective or most Pythonic method for converting them to a dictionary with the names as keys and and values as the values?

Here's what I've come up. It's pretty short and seems to work fine, but is there some built-in function for doing just this sort of thing?

verbose_attributes = [
    {
        'Name': 'id',
        'Value': 'd3f23fa5'
    },
    {
        'Name': 'first_name',
        'Value': 'Guido'
    },
    {
        'Name': 'last_name',
        'Value': 'van Rossum'
    }]

attributes = {}

for pair in verbose_attributes:
    attributes[pair['Name']] = pair['Value']

print(repr(attributes))
# {'id': 'd3f23fa5', 'first_name': 'Guido', 'last_name': 'van Rossum'}

In short, is there a better way of converting verbose_attributes to attributes ?

使用字典理解:

attributes = {x['Name']: x['Value'] for x in verbose_attributes}

Using map and dict.values

>>> dict(map(dict.values, verbose_attributes))
{'id': 'd3f23fa5', 'first_name': 'Guido', 'last_name': 'van Rossum'}

Yet another way using map and operator.itemgetter

>>> from operator import itemgetter
>>> dict(map(itemgetter('Name', 'Value'), verbose_attributes))
{'first_name': 'Guido', 'last_name': 'van Rossum', 'id': 'd3f23fa5'}

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