简体   繁体   中英

How to make all combinations from a dictionary in python

I have a following dictionary:

origin = {0: [1,2], 1: [1,2,3]}

I would like to get a dictionary that makes combination key_element in value. Desired output is:

{'combo_0_1': 0, 'combo_0_2': 0, 'combo_1_1': 0, 'combo_1_2': 0, 'combo_1_3': 0}

I tried this:

output = {f"combo_{x}_{y}" : 0 for x in origin.keys() for y in origin.values()}

but it returns {'combo_0_[1, 2]': 0, 'combo_0_[1, 2, 3]': 0, 'combo_1_[1, 2]': 0, 'combo_1_[1, 2, 3]': 0} which is not what I want. How can I do it, please?

origin.values() returns all the values, which are lists. This is not what you want.

You want the elements of the current list.

output = {f"combo_{x}_{y}" : 0 for x in origin.keys() for y in origin[x]}

It helps to write it out as a full loop first. We can convert it to a dict comprehension after that.

You want the second part of the key to be each element of each value of origin . You can get the keys and values of origin in one outer loop, and then in the inner loop, you can loop over the elements in that value.

origin = {0: [1,2], 1: [1,2,3]}
output = {}
for key, val in origin.items():
    for elem in val:
        output[f"combo_{key}_{elem}"] = 0

Or, as a dict comprehension:

output = {f"combo_{key}_{elem}": 0 for key, val in origin.items() for elem in val}

This gives:

{'combo_0_1': 0,
 'combo_0_2': 0,
 'combo_1_1': 0,
 'combo_1_2': 0,
 'combo_1_3': 0}

One approach using a dictionary comprehension over dict.items :

origin = {0: [1, 2], 1: [1, 2, 3]}

res = {f"combo_{k}_{v}": 0 for k, vs in origin.items() for v in vs}
print(res)

Output

{'combo_0_1': 0, 'combo_0_2': 0, 'combo_1_1': 0, 'combo_1_2': 0, 'combo_1_3': 0}

Here's my solution. It generates all the permutations of your lists, and is generalized to accept longer dictionaries.

import itertools

origin = {0: [1,2], 1: [1,2,3]}
perms = list(itertools.product(*origin.values()))
output = {f"combo_"+ "_".join(map(str,p)): 0 for p in perms}
print(output)

Note: You need to map the tuples which itertools.product generates to strings to join them together to your "combo_" keys. Hope this helps!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM