use*_*993 -5 python dictionary list python-2.7
我甚至不确定该怎么称呼它,所以很难搜索.我有,例如,
people = [
{"age": 22, "first": "John", "last": "Smith"},
{"age": 22, "first": "Jane", "last": "Doe"},
{"age": 41, "first": "Brian", "last": "Johnson"},
]
Run Code Online (Sandbox Code Playgroud)
我想要类似的东西
people_by_age = {
22: [
{"first": "John", "last": "Smith"},
{"first": "Jane", "last": "Doe"},
],
41: [
{"first": "Brian", "last": "Johnson"}
]
}
Run Code Online (Sandbox Code Playgroud)
在Python 2中最干净的方法是什么?
只需循环并添加到新词典:
people_by_age = {}
for person in people:
age = person.pop('age')
people_by_age.setdefault(age, []).append(person)
Run Code Online (Sandbox Code Playgroud)
该dict.setdefault()方法返回给定键的现有值,或者如果缺少键,则使用第二个参数首先设置该键.
演示:
>>> 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'}]}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
68 次 |
| 最近记录: |