0

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

Tony Piazza
  • 335
  • 1
  • 2
  • 12

2 Answers2

2

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.

Tony Piazza
  • 335
  • 1
  • 2
  • 12
0

You can instantiate a dict with the generator output of the values() method on each dict in the list:

dict(d.values() for d in l)
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • This requires the values be enumerated in a specific order. That is an invalid assumption. The items returned by the `values()` method will be in a random order prior to python 3.7. And even in python 3.7 the order depends on the order in which the keys were inserted. – Kurtis Rader Aug 19 '18 at 21:09