Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']
like image 353
RonnyKnoxville Avatar asked Jan 12 '12 10:01

RonnyKnoxville


1 Answers

This is simple using a defaultdict:

persons_by_jobs = defaultdict(list)
for person in persons:
    persons_by_jobs[person['job']].append(person['person'])
like image 94
Björn Pollex Avatar answered Oct 23 '22 04:10

Björn Pollex