简体   繁体   English

Pythonic名称/值对到字典转换

[英]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? 给定一系列由名称-值对组成的字典,将它们转换为以名称为键,值作为值的字典的最有效或最Pythonic方法是什么?

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 ? 简而言之,是否有更好的方法将verbose_attributes转换为attributes

使用字典理解:

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

Using map and dict.values 使用mapdict.values

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

Yet another way using map and operator.itemgetter 使用mapoperator.itemgetter另一种方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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