问题
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'}
回答1:
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'}]
回答2:
You need to iterate through the value-list at key 'mount'
, and update the value at that key:
>>> data = {'cluster': 'A', 'node': 'B', 'mount': ['C', 'D', 'E']}
>>>
>>> for v in data['mount']:
... d = data.copy()
... d['mount'] = v
... print(d)
...
{'node': 'B', 'cluster': 'A', 'mount': 'C'}
{'node': 'B', 'cluster': 'A', 'mount': 'D'}
{'node': 'B', 'cluster': 'A', 'mount': 'E'}
You could also build all the dicts in a list using a list comprehension given the value-list location is already known:
>>> [{'cluster': 'A', 'node': 'B', 'mount': v} for v in data['mount']]
[{'node': 'B', 'cluster': 'A', 'mount': 'C'},
{'node': 'B', 'cluster': 'A', 'mount': 'D'},
{'node': 'B', 'cluster': 'A', 'mount': 'E'}]
来源:https://stackoverflow.com/questions/46044751/split-dictionary-based-on-values