代码之家  ›  专栏  ›  技术社区  ›  WhiteHotLoveTiger

pythonic名称-值对到字典的转换

  •  0
  • WhiteHotLoveTiger  · 技术社区  · 7 年前

    给定一组名称-值对的dict,将它们转换为名称为键、值为值的字典的最有效或最简单的方法是什么?

    这就是我想说的。它很短,似乎工作得很好,但是是否有一些内置的功能可以完成这类工作?

    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'}
    

    简而言之,有没有更好的转换方式 verbose_attributes attributes ?

    2 回复  |  直到 7 年前
        1
  •  7
  •   Austin    7 年前

    使用字典理解:

    attributes = {x['Name']: x['Value'] for x in verbose_attributes}
    
        2
  •  2
  •   Sunitha    7 年前

    使用 map dict.values

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

    另一种方法是 地图 operator.itemgetter

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