Skip to content
Advertisement

Expand a dict containing list items into a list of dict pairs

If I have a dictionary containing lists in one or more of its values:

data = {
  'a':0,
  'b':1,
  'c':[0, 1, 2],
  'pair':['one','two']
}

How can I get a list of dict tuples paired by pair and iterating over c, with all else remaining constant? E.g.

output = [
    ({
        'a':0,
        'b':1,
        'c':0,
        'pair':'one'
    },
    {
        'a':0,
        'b':1,
        'c':0,
        'pair':'two'
    }),
    ({
        'a':0,
        'b':1,
        'c':1,
        'pair':'one'
    },
    ...
]

Advertisement

Answer

Well, this doesn’t feel especially elegant, but you might use a nested for loop or list comprehension:

output = []
for i in data['c']:
  output.append(tuple({'a': 0, 'b': 1, 'c': i, 'pair': p} for p in data))

or

output = [tuple({'a': 0, 'b': 1, 'c': i, 'pair': p} for p in data['pair']) for i in data['c']]

A cleaner solution might separate out the generation of the component dict into a function, like this:

def gen_output_dict(c, pair):
  return {'a': 0, 'b': 1, 'c': c, 'pair': pair}

output = []
for i in data['c']:
  output.append(tuple(gen_output_dict(i, p) for p in data['pair']))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement