Python 将一个目录列表映射成一个目录列表
我甚至不知道该怎么称呼它,所以很难找到它。比如我有,Python 将一个目录列表映射成一个目录列表,python,list,python-2.7,dictionary,Python,List,Python 2.7,Dictionary,我甚至不知道该怎么称呼它,所以很难找到它。比如我有, people = [ {"age": 22, "first": "John", "last": "Smith"}, {"age": 22, "first": "Jane", "last": "Doe"}, {"age": 41, "first": "Brian", "last": "Johnson"}, ] 我想要像这样的东西 people_by_age = { 22: [ {"first":
people = [
{"age": 22, "first": "John", "last": "Smith"},
{"age": 22, "first": "Jane", "last": "Doe"},
{"age": 41, "first": "Brian", "last": "Johnson"},
]
我想要像这样的东西
people_by_age = {
22: [
{"first": "John", "last": "Smith"},
{"first": "Jane", "last": "Doe"},
],
41: [
{"first": "Brian", "last": "Johnson"}
]
}
在Python 2中,最干净的方法是什么?只需循环并添加到新字典中:
people_by_age = {}
for person in people:
age = person.pop('age')
people_by_age.setdefault(age, []).append(person)
返回给定键的现有值,或者如果缺少该键,则使用第二个参数首先设置该键
演示:
使用方法和步骤
代码:
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)
defaultdict(<type 'list'>, {41: [{'last': 'Johnson', 'first': 'Brian'}], 22: [{'last': 'Smith', 'first': 'John'}, {'last': 'Doe', 'first': 'Jane'}]})
输出:
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)
defaultdict(<type 'list'>, {41: [{'last': 'Johnson', 'first': 'Brian'}], 22: [{'last': 'Smith', 'first': 'John'}, {'last': 'Doe', 'first': 'Jane'}]})
defaultdict(,{41:[{'last':'Johnson','first':'Brian'}],22:[{'last':'Smith','first':'John'},{'last':'Doe','first':'Jane'})
谢谢!这完全回答了我的问题。