I am relatively new to Python (itself, using 3.8) and stackoverflow. I have searched google and here a lot but cannot find a clue.
I have a dictionary with a different number of keys in tuples. Values are always one string. Here, I simplified the code. Actual dictionary has around 2000 keys.
{('A', 'B', 'C', 'D', 'E'): 'fruit', ( 'F', 'G', 'H'): 'veg', ('I', ): 'meet'}
This is what I want.
{'A': 'fruit', 'B': 'fruit', 'C': 'fruit', 'D': 'fruit', 'E': 'fruit', 'F': 'veg', 'G': 'veg', 'H': 'veg', 'I': 'meet'}
I tried to change the tuple into a list, repeat values up to len(i in tuple) and zip, etc. but I cannot combine keys and values one-on-one. Would you help me out?
CodePudding user response:
d = {('A', 'B', 'C', 'D', 'E'): 'fruit', ( 'F', 'G', 'H'): 'veg', ('I', ): 'meet'}
Each key is a tuple. For each element in this tuple, we want one key in our result. The value will be the original value.
res = {elem: val
for key, val in d.items()
for elem in key}