Search code examples
pythonpython-3.xpython-itertools

Itertools Group list of dicts of variable length by key/value pairs


I have this input object:

vv = [{'values': ['AirportEnclosed', 'Bus', 'MotorwayServiceStation']},{'values': ['All']}]

...there can be variable numbers of dicts present, but all dicts will always have the key 'values' and values populated for this.

The type of value assigned to 'values' will always be string or list. I wish to group/zip so I get the following output (list of tuples or tuple of tuples is fine):

(
('AirportEnclosed', 'All'),
('Bus', 'All'),
('MotorwayServiceStation', 'All')
)

...this is my code:

import itertools

outputList=[]
for i,g in itertools.groupby(vv, key=operator.itemgetter("values")):
    outputList.append(list(g))
print(outputList) 

...and this is my output:

[[{'values': ['AirportEnclosed', 'Bus', 'MotorwayServiceStation']}], [{'values': ['All']}]]

...what do I need to change?


Solution

  • import itertools as it
    
    vv = [{'values': ['AirportEnclosed', 'Bus', 'MotorwayServiceStation']}, 
    {'values': ['All']}]
    
    tmp = []
    
    for curr_dict in vv:
        val = curr_dict["values"]
        if type(val) == str:
            val = [val]
        tmp.append(val)
    
    pr = it.product(*tmp)
    out = []
    
    for i in pr:
        out.append(i)