If I have a dictionary containing lists in one or more of its values:
JavaScript
x
7
1
data = {
2
'a':0,
3
'b':1,
4
'c':[0, 1, 2],
5
'pair':['one','two']
6
}
7
How can I get a list of dict tuples paired by pair
and iterating over c
, with all else remaining constant? E.g.
JavaScript
1
22
22
1
output = [
2
({
3
'a':0,
4
'b':1,
5
'c':0,
6
'pair':'one'
7
},
8
{
9
'a':0,
10
'b':1,
11
'c':0,
12
'pair':'two'
13
}),
14
({
15
'a':0,
16
'b':1,
17
'c':1,
18
'pair':'one'
19
},
20
21
]
22
Advertisement
Answer
Well, this doesn’t feel especially elegant, but you might use a nested for loop or list comprehension:
JavaScript
1
4
1
output = []
2
for i in data['c']:
3
output.append(tuple({'a': 0, 'b': 1, 'c': i, 'pair': p} for p in data))
4
or
JavaScript
1
2
1
output = [tuple({'a': 0, 'b': 1, 'c': i, 'pair': p} for p in data['pair']) for i in data['c']]
2
A cleaner solution might separate out the generation of the component dict into a function, like this:
JavaScript
1
7
1
def gen_output_dict(c, pair):
2
return {'a': 0, 'b': 1, 'c': c, 'pair': pair}
3
4
output = []
5
for i in data['c']:
6
output.append(tuple(gen_output_dict(i, p) for p in data['pair']))
7