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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With