Unpacking a dictionary's tuple keys into individual keys using dictionary comprehension in Python

Viewed 1344

Assuming a dictionary where the keys are tuples:

D = {
    ('a','b') : 1,
    ('x','y','z') : 2
}

How can I split each tuple-key into separate keys with the same value:

N = {
    'a' : 1, 'b' : 1,
    'x' : 2, 'y' : 2, 'z' : 2
}

In a single dictionary comprehension. I've drafted up the following line, but I'm wondering if it's possible to shorten it and not create a proxy value list of the same length as the key tuple.

N = { k:v for s in ( zip(keys,[value]*len(keys)) for keys,value in D.items() ) for k,v in s }
2 Answers

The nested comprehension you are looking for looks like this:

>>> D = {
...:    ('a','b') : 1,
...:    ('x','y','z') : 2
...:}
>>> 
>>> {k_i:v for k, v in D.items() for k_i in k}
>>> {'a': 1, 'b': 1, 'x': 2, 'y': 2, 'z': 2}

which could be written with traditional for loops like this:

>>> result = {}
>>> for k, v in D.items():
...:    for k_i in k:
...:        result[k_i] = v
...:        
>>> result
>>> {'a': 1, 'b': 1, 'x': 2, 'y': 2, 'z': 2}

Bonus: itertools abuse!

>>> from itertools import repeat, chain
>>> dict(chain.from_iterable(zip(k, repeat(v)) for k, v in D.items()))
>>> {'a': 1, 'b': 1, 'x': 2, 'y': 2, 'z': 2}

You can use a dict comprehension like this:

{k: v for t, v in D.items() for k in t}
Related