I have a dictionary:
data = {'cluster': 'A', 'node': 'B', 'mount': ['C', 'D', 'E']}
I'm trying to split the dictionary data
into number of dictionaries based on values in key mount
.
I tried using:
for value in data.items():print(data)
But I get this:
data = {'cluster': 'A', 'node': 'B', 'mount': ['C', 'D', 'E']}
data = {'cluster': 'A', 'node': 'B', 'mount': ['C', 'D', 'E']}
data = {'cluster': 'A', 'node': 'B', 'mount': ['C', 'D', 'E']}
Actually, I would like to get:
data = {'cluster': 'A', 'node': 'B', 'mount': 'C'}
data = {'cluster': 'A', 'node': 'B', 'mount': 'D'}
data = {'cluster': 'A', 'node': 'B', 'mount': 'E'}
You could use a list comprehension with itertools.product
:
>>> from itertools import product
>>> [dict(zip(data.keys(), prod)) for prod in product(*data.values())]
[{'cluster': 'A', 'mount': 'C', 'node': 'B'},{'cluster': 'A', 'mount': 'D', 'node': 'B'},{'cluster': 'A', 'mount': 'E', 'node': 'B'}]
It would even work if another variable contains a list:
>>> data = {'cluster': ['A', 'B'], 'node': 'B', 'mount': ['C', 'D', 'E']}
>>> [dict(zip(data.keys(), prod)) for prod in product(*data.values())]
[{'cluster': 'A', 'mount': 'C', 'node': 'B'},{'cluster': 'B', 'mount': 'C', 'node': 'B'},{'cluster': 'A', 'mount': 'D', 'node': 'B'},{'cluster': 'B', 'mount': 'D', 'node': 'B'},{'cluster': 'A', 'mount': 'E', 'node': 'B'},{'cluster': 'B', 'mount': 'E', 'node': 'B'}]