Switch key and value in a dictionary of sets

goldenasian :

I have dictionary something like:

d1 = {'0': {'a'}, '1': {'b'}, '2': {'c', 'd'}, '3': {'E','F','G'}}

and I want result like this

d2 = {'a': '0', 'b': '1', 'c': '2', 'd': '2', 'E': '3', 'F': '3', 'G': '3'}

so I tried

d2 = dict ((v, k) for k, v in d1.items())

but value is surrounded by set{}, so it didn't work well... is there any way that I can fix it?

yatu :

You could use a dictionary comprehension:

{v:k for k,vals in d1.items() for v in vals}
# {'a': '0', 'b': '1', 'c': '2', 'd': '2', 'E': '3', 'F': '3', 'G': '3'}

Note that you need an extra level of iteration over the values in each key here to get a flat dictionary.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360145&siteId=1