简体   繁体   中英

Best way to sort a dictionary into groups using Python

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']

This is simple using a defaultdict :

persons_by_jobs = defaultdict(list)
for person in persons:
    persons_by_jobs[person['job']].append(person['person'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM