简体   繁体   中英

Python: Grouping dictionary based on passed tuple (all tuple elements)

Let's assume I have passed a list of dictionaries [{d}] and tuple (t) to a function, where the length of tuple can be arbitrary (eg, i have a group function which passes in a dictionary and a tuple and returns grouped dictionary):

def group([{d}], (t)):
    ...
    return by_group

The elements of tuple are among the keys of dictionary.

How can I group dictionaries based on keys provided by tuple (t)?

E,g.: if

d = [{'name': 'John', 'cat': 'senior', 'pos': 'fwd'}, {'name': 'Adam', 'cat': 'junior', 'pos': 'fwd'}, {'name': 'Bruce', 'cat': 'senior', 'pos': 'fwd'}]
t = ('cat', 'pos')

then

by_group = { ('senior', 'fwd'): [{'name': 'John', 'cat': 'senior', 'pos': 'fwd'}, {'name': 'Bruce', 'cat': 'senior', 'pos': 'fwd'}], ('junior', 'def'): [{'name': 'Adam', 'cat': 'junior', 'pos': 'fwd'}] }

You can use itertools.groupby and dictionary comprehension for this.

import itertools

d.sort(key=lambda x: tuple(x[key] for key in t))  # sorting the data with the same key before grouping.

by_group = {
    key: [g for g in group]
    for key, group in itertools.groupby(d, key=lambda x: tuple(x[key] for key in t))
}

Output:

{
    ("junior", "fwd"): [{"name": "Adam", "cat": "junior", "pos": "fwd"}],
    ("senior", "fwd"): [
        {"name": "John", "cat": "senior", "pos": "fwd"},
        {"name": "Bruce", "cat": "senior", "pos": "fwd"},
    ],
}

I solved it:

def group_by_field(d, t):
    group_keys = { tuple( s[key] for key in t ) for s in d }
    by_group = { key: [] for key in group_keys }
    for el in d:
        by_group[ tuple( el[key] for key in t) ].append(el)
    return by_group

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM