I have a list of dictionaries eg:
我有一份字典目录。
[{'person':'guybrush','job':'pirate'},{'person':'leChuck','job':'pirate'}, {'person':'elaine','job':'governor'}]
I want to display the people grouped by their jobs. So in the front end, we can select a job and see all of the people that have the selected job.
我想展示按工作分组的人。因此,在前端,我们可以选择一份工作,并看到所有有选择的工作的人。
I have performed such a function before using confusing nested loops and lists.
在使用混乱的嵌套循环和列表之前,我已经执行了这样一个函数。
What do you think is the most efficient way of getting this result?
你认为得到这个结果最有效的方法是什么?
pirate = ['guybrush','leChuck']
governor = ['elaine']
1 个解决方案
#1
21
This is simple using a defaultdict
:
这很简单,使用默认命令:
persons_by_jobs = defaultdict(list)
for person in persons:
persons_by_jobs[person['job']].append(person['person'])
#1
21
This is simple using a defaultdict
:
这很简单,使用默认命令:
persons_by_jobs = defaultdict(list)
for person in persons:
persons_by_jobs[person['job']].append(person['person'])