Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14126

Python itertools.product challenge

$
0
0

Given a dictionary like this with some items being tuples...

params = {'a': 'static','b': (1, 2),'c': ('X', 'Y')}

I need the "product" of the tuples being expanded like this...

[{'a': 'static','b': 1,             <<< each item in b, must be matched with each item in c'c': 'X'    },    {'a': 'static','b': 1,'c': 'Y')    },    [{'a': 'static','b': 2,'c': 'X'    },    {'a': 'static','b': 2,'c': 'Y')}]

I can easily separate the initial input into a list of non-tuple items and tuple items, and apply the key of each tuple to the values as a "tag" prior to multiplication so they look like this: 'b##1', 'b##2', 'c##X', 'c##Y'. Then parse those back into the above dict after multiplication. If I would always see 2 tuple items (like b and c), I could easily pass both to itertools.products. But there could be 0..n tuple items, and product() doesn't multiply a list of lists in this way. Can anyone think of a solution?

TAG = '@@'# separate tuples and non-tuples from the input, and prepend the key of each tuple as a tag on the value to parse out laterfor key, value in params.items():    if type(value) is tuple:        for x in value:            tuples.append(f'{key}{TAG}{x}')    else:        non_tuples.append({key: value})print(list(product(tuples))      # BUG: doesn't distribute each value of b with each value of c

Viewing all articles
Browse latest Browse all 14126

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>