2

I have a list of dictionaries that looks like the following:

d = [{'first':'jason','color':'green','age':22},
     {'first':'josh','color':'red','age':22},
     {'first':'chris','color':'blue','age':21}
    ]

I want to create a dictionary that is a subset of the previous dictionaries.

Something that looks like:

newD = {'jason':22, 'josh':22, 'chris':21}

The following does the trick:

first = [k['first'] for k in d]
age = [k['age'] for k in d]
newD = dict(zip(first, age))

But is there a more Pythonic/cleaner way to do this?

jadki
  • 482
  • 1
  • 8
  • 15

4 Answers4

6
newd = {dd['first']: dd['age'] for dd in d}

Output:

In [3]: newd
Out[3]: {'chris': 21, 'jason': 22, 'josh': 22}
Osman Mamun
  • 2,864
  • 1
  • 16
  • 22
3

Yes, you only need one comprehension:

>>> {x['first']: x['age'] for x in d}
{'jason': 22, 'josh': 22, 'chris': 21}
wim
  • 338,267
  • 99
  • 616
  • 750
3

Maybe this?

newD = dict((x['first'], x['age']) for x in d)
Sufian Latif
  • 13,086
  • 3
  • 33
  • 70
2

Using operator.itemgetter:

from operator import itemgetter

res = dict(map(itemgetter('first', 'age'), d))

{'jason': 22, 'josh': 22, 'chris': 21}
jpp
  • 159,742
  • 34
  • 281
  • 339