Ask Your Question

How can I divide the query results into several objects by using one column with Python?

asked 2021-09-03 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-10-05 20:00:00 +0000

huitzilopochtli gravatar image

You can use Python's groupby() function to group the query results by a specific column. Here's an example:

Assuming you have a list of dictionaries, where each dictionary represents a row from the query results:

query_results = [
    {'id': 1, 'name': 'John', 'age': 25},
    {'id': 2, 'name': 'Jane', 'age': 30},
    {'id': 3, 'name': 'Bob', 'age': 25},
    {'id': 4, 'name': 'Sue', 'age': 30}

If you want to group the results by age, you can use the following code:

from itertools import groupby

query_results.sort(key=lambda x: x['age'])

grouped_results = {}
for key, group in groupby(query_results, lambda x: x['age']):
    grouped_results[key] = list(group)


This will produce the following output:

    25: [
        {'id': 1, 'name': 'John', 'age': 25},
        {'id': 3, 'name': 'Bob', 'age': 25}
    30: [
        {'id': 2, 'name': 'Jane', 'age': 30},
        {'id': 4, 'name': 'Sue', 'age': 30}

In this example, the query results are first sorted by age using lambda function. The groupby() function from itertools is then used to group the results by age, creating a dictionary where each key is the age and the value is a list of objects with that age.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools


Asked: 2021-09-03 11:00:00 +0000

Seen: 14 times

Last updated: Oct 05 '22