Python Forum
How to unpack tuples in if statements - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to unpack tuples in if statements (/thread-18086.html)



How to unpack tuples in if statements - saurkkum - May-05-2019

I am trying to write a function that accepts a list of dictionary (data) and a tuple (fields). Function groups the data based on elements in fields tuple. Since I do not know how many elements will be there in the tuple, how could I re-write this function so that it works for any number of items in the fields tuple.

def group_by_field(data, fields):
    groups = {}
    
    for item in data:
        if (item[fields[0]],item[fields[1]]) in groups:
            groups[item[fields[0]],item[fields[1]]].append(item)
        else:
            groups[item[fields[0]],item[fields[1]]] = []
            groups[item[fields[0]],item[fields[1]]].append(item)
    
    return groups



RE: How to unpack tuples in if statements - Gribouillis - May-05-2019

I suggest two versions
from collections import defaultdict

def group_by_fields2(data, fields):
    groups = defaultdict(list)
    for item in data:
        key = tuple(item[f] for f in fields)
        groups[key].append(item)
    return groups
and this one, which may not preserve the initial ordering of the dictionaries
from itertools import groupby

def group_by_fields3(data, fields):
    def key(item): return tuple(item[f] for f in fields)
    return {k: list(g) for k, g in groupby(sorted(data, key=key),key=key)}
The first version can be refactored a little by providing a more general function
from collections import defaultdict

def group_by(data, key):
    groups = defaultdict(list):
    for item in data:
        groups[key(item)].append(item)
    return dict(groups)

def group_by_fields4(data, fields):
    return group_by(data, lambda item: tuple(item[f] for f in fields))