Friends, basically, I want to take a dict:
fruit_dict = {'oranges':['big','small'],'apples':['green','yellow','red']}
And get the following list of dictionaries by having all possible permutations between all values of different keys:
output_list =
[
{'oranges':'big','apples':'green'},
{'oranges':'big','apples':'yellow'},
{'oranges':'big','apples':'red'},
{'oranges':'small','apples':'green'},
{'oranges':'small','apples':'yellow'},
{'oranges':'small','apples':'red'}
]
How to do it? Thanks a million!
What you're looking for isn't the permutations, but the Cartesian product . Think of it like a nested loop.
from itertools import product
fruit_dict = {'oranges':['big','small'],'apples':['green','yellow','red']}
keys, values = zip(*fruit_dict.items())
print [dict(zip(keys, value_list)) for value_list in product(*values)]
Then you just need to create a new dictionary using your existing keys and each item from the product.
using itertools.product()
:
In [94]: dic = {'oranges':['big','small'],'apples':['green','yellow','red']}
In [95]: sort_values=[x[1] for x in sorted(dic.items())] #sorted values based on keys
In [96]: [dict(zip(sorted(dic.keys()),x)) for x in product(*sort_values)]
Out[96]:
[{'apples': 'green', 'oranges': 'big'},
{'apples': 'green', 'oranges': 'small'},
{'apples': 'yellow', 'oranges': 'big'},
{'apples': 'yellow', 'oranges': 'small'},
{'apples': 'red', 'oranges': 'big'},
{'apples': 'red', 'oranges': 'small'}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.