Search code examples
pythonpython-3.xpython-zip

How to zip keys within a list of dicts


I have this object:

dvalues = [{'column': 'Environment', 'parse_type': 'iter', 'values': ['AirportEnclosed', 'Bus', 'MotorwayServiceStation']}, {'column': 'Frame Type', 'parse_type': 'list', 'values': ['All']}]

I want a zipped output like this:

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

so far the nearest I have got is with the below:

for d in dvalue:
    dv = d['values']
    zip_list = zip(dv, d['values'])
    for z in zip_list:
        print(z)

Which gives me this as an output:

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

What do I need to change to get the desired output?


Solution

  • I am not sure if I understand the underlying reasoning, nor how general of a solutions you want (are the dictionaries always two, or can they be more?). Here is something to get you started:

    dvalues = [{'column': 'Environment', 'parse_type': 'iter', 'values': ['AirportEnclosed', 'Bus', 'MotorwayServiceStation']}, {'column': 'Frame Type', 'parse_type': 'list', 'values': ['All']}]
    
    import itertools
    
    la = dvalues[0]['values']
    lb = dvalues[1]['values']
    
    print([(x, y) for x,y in zip(la, itertools.cycle(lb))])
    

    This gives the desired output:

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

    Inspired from: Loop over 2 lists, repeating the shortest until end of longest