-5

I'm not even sure what to call this, so it's difficult to search for. I have, for example,

people = [
    {"age": 22, "first": "John", "last": "Smith"},
    {"age": 22, "first": "Jane", "last": "Doe"},
    {"age": 41, "first": "Brian", "last": "Johnson"},
]

And I want something like

people_by_age = {
    22: [
        {"first": "John", "last": "Smith"},
        {"first": "Jane", "last": "Doe"},

    ],
    41: [
        {"first": "Brian", "last": "Johnson"}
    ]
}

What's the cleanest way to do this in Python 2?

user280993
  • 461
  • 1
  • 5
  • 5

2 Answers2

6

Just loop and add to a new dictionary:

people_by_age = {}
for person in people:
    age = person.pop('age')
    people_by_age.setdefault(age, []).append(person)

The dict.setdefault() method either returns the already existing value for the given key, or if the key is missing, uses the second argument to set that key first.

Demo:

>>> people = [
...     {"age": 22, "first": "John", "last": "Smith"},
...     {"age": 22, "first": "Jane", "last": "Doe"},
...     {"age": 41, "first": "Brian", "last": "Johnson"},
... ]
>>> people_by_age = {}
>>> for person in people:
...     age = person.pop('age')
...     people_by_age.setdefault(age, []).append(person)
... 
>>> people_by_age
{41: [{'last': 'Johnson', 'first': 'Brian'}], 22: [{'last': 'Smith', 'first': 'John'}, {'last': 'Doe', 'first': 'Jane'}]}
>>> from pprint import pprint
>>> pprint(people_by_age)
{22: [{'first': 'John', 'last': 'Smith'}, {'first': 'Jane', 'last': 'Doe'}],
 41: [{'first': 'Brian', 'last': 'Johnson'}]}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

Using defaultdict method and dictonary.pop method

Code:

from collections import defaultdict

people = [
    {"age": 22, "first": "John", "last": "Smith"},
    {"age": 22, "first": "Jane", "last": "Doe"},
    {"age": 41, "first": "Brian", "last": "Johnson"},
]

d = defaultdict(int)

people_dic = defaultdict(list)
for element in people:
    age = element.pop('age')
    people_dic[age].append(element)

print(people_dic)

Output:

defaultdict(<type 'list'>, {41: [{'last': 'Johnson', 'first': 'Brian'}], 22: [{'last': 'Smith', 'first': 'John'}, {'last': 'Doe', 'first': 'Jane'}]})
Community
  • 1
  • 1
The6thSense
  • 8,103
  • 8
  • 31
  • 65