Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to group python dicts by key?

We have a list of dictionaries:

example = [
    {'a': 11, 'b': 2, 'c': 3},
    {'a': 11, 'b': 22, 'c': 33},
    {'a': 11, 'b': 222, 'c': 333}
]

How to group the dictionaries by repeating key a?

example = {
    11: [
        {'b': 2, 'c': 3},
        {'b': 22, 'c': 33},
        {'b': 222, 'c': 333}
    ]
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Grouping can be done using itertools.groupby.

Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.

from itertools import groupby

example = [
    {'a': 11, 'b': 2, 'c': 3},
    {'a': 11, 'b': 22, 'c': 33},
    {'a': 11, 'b': 222, 'c': 333}
]

for k, g in groupby(example, key=lambda v: v.pop("a", None)):
    print(k, list(g))

Output:

11 [{'b': 2, 'c': 3}, {'b': 22, 'c': 33}, {'b': 222, 'c': 333}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading