简体   繁体   中英

Creating dictionary with tuple keys with a loop

I'm trying to create a dictionary with tuples as keys.

For example, if my range is (0, 3), I want to create a dictionary with mappings of every combination. Eg {(0,0):1, (0,1):2, (0,2):1 ...} , where the value is an int that does not exist in the tuple.

If the range were (0, 4) the dictionary would look something like this:

{(0,1,2):3, (0,0,0):1, (0,0,1):2...}

The only rule being that the key must be a value that is not contained in the tuple and is within the given range.

Hopefully, that makes sense. I've been trying to figure out how to write code in python to do this, but I'm not sure how to go about this.

Edit Complete Example: Range: (0, 3)

Dict Created:

{(0,0):1, (0,1):2, (0,2):1, (1,0):2, (1,1):2, (1,2): 0, (2,0): 1, (2,1):0, (2:2):1} 

And yes, for some combinations eg (1,1) there are multiple possible values. It could be (1,1): 0 or (1,1): 2 . I just need one though.

With itertools.product you could create all the keys. Then you just need to find one value that is in your range but not in the key, which could be solved using set.difference :

>>> import itertools

>>> the_range = range(0, 3)
>>> possible = set(the_range)

>>> {key: possible.difference(key).pop() for key in itertools.product(the_range, repeat=len(the_range)-1)}
{(0, 1): 2, (1, 2): 0, (0, 0): 1, (2, 0): 1, (1, 0): 2, (2, 2): 0, (0, 2): 1, (2, 1): 0, (1, 1): 0}

It should work as long as you don't expect a specific value from the difference. Sets are un-ordered so the set.pop approach will always give a "random" value from the "remaining" ones.

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