Joey Coder
Joey Coder

Reputation: 3519

Group list by specific key in that list

I have the following QuerySet result as a list:

<QuerySet [{'answer__question__focus': 'hearing_about_the_event', 'name': 'Facebook', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'hearing_about_the_event', 'name': 'Instagram', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'hearing_about_the_event', 'name': 'friends', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'missing_event_information', 'name': 'Line-up', 'count': 2, 'total_salience': 2.0}, {'answer__question__focus': 'missing_event_information', 'name': 'food', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'reason_for_attending', 'name': 'girlfriend', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'type_of_people_attending', 'name': 'incomes', 'count': 3, 'total_salience': 2.26287645101547}, {'answer__question__focus': 'type_of_people_attending', 'name': 'people', 'count': 1, 'total_salience': 1.0}]>

I now attempt to group this result in my Django application by answer__question__focus with Python. However, I struggle to get my data in the right order/format. How can I do so in an efficient way?

[
    'hearing_about_the_event':  # question.pk
    [
        {
            'name': 'Leonardo Di Caprio',
            'count': 4,
            'salience': 3.434
        },
        {
            'name': 'titanic',
            'count': 5,
            'salience': 1.12
        },
        {
            'name': 'music',
            'count': 3,
            'salience': 1.12
        }
    ],
    'missing_event_information':  # question.pk
    [
        {
            'name': 'Leonardo Di Caprio',
            'count': 5,
            'salience': 1.5
        },
        {
            'name': 'titanic',
            'count': 4,
            'salience': 1.12
        },
        {
            'name': 'music',
            'count': 2,
            'salience': 1.12
        }
    ]
]

Upvotes: 0

Views: 64

Answers (2)

halfer
halfer

Reputation: 20469

(Posted on behalf of the question author, in order to move it from the question post).

Here is my solution. Thanks to @Julien Kieffer

d = defaultdict(list)
for entity in entities:
    question_focus = entity.pop("answer__question__focus")
    d[question_focus].append(entity)

Upvotes: 0

Julien Kieffer
Julien Kieffer

Reputation: 1145

You can do this using a combination of reduce and defaultdict.

Below code is for python 3.

from functools import reduce
from collections import defaultdict

def aggregate(data, item):
    key = item.pop('answer__question__focus')
    data[key].append(item)
    return data

data = reduce(aggregate,qs, defaultdict(list))

Upvotes: 2

Related Questions