只需循環,並添加到新詞典:
people_by_age = {}
for person in people:
age = person.pop('age')
people_by_age.setdefault(age, []).append(person)
的dict.setdefault()
method或者返回給定鍵已經存在的價值,或者如果密鑰丟失,使用第二個參數,首先設置鍵。
演示:
>>> 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'}]}
謝謝!這完美地回答了我的問題。 – user280993