0

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?

WhiteHotLoveTiger
  • 2,088
  • 3
  • 30
  • 41
  • 1
    You can pass a set of `(key, value)` tuples to the `dict` constructor. I think you're looking for `dict(((x['Name'], x['Value']) for x in verbose_attributes))`. **Edit**: Another option is `dict(x.values() for x in verbose_attributes)` – pault Jul 23 '18 at 18:36
  • 1
    I don't think there's anything wrong with what you have, personally. It's readable and gets the job done. – mypetlion Jul 23 '18 at 18:38

2 Answers2

7

Use a dictionary-comprehension:

attributes = {x['Name']: x['Value'] for x in verbose_attributes}
Austin
  • 25,759
  • 4
  • 25
  • 48
2

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'}
Sunitha
  • 11,777
  • 2
  • 20
  • 23