May-05-2019, 09:15 AM
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