1

Sorry, if this one is duplicate, but I am new to python and haven't found solution by googling.

I have a dictionary that looks like:

{
   1 : ['x', 'y'],
   2 : ['z'],
   3 : ['a']
}

All values in lists are guaranteed to be unique. And I want to transform this dictionary to:

{
   'x' : 1,
   'y' : 1,
   'z' : 2,
   'a' : 3
}

What is the most pythonic and clean way to write this?

2 Answers2

2

Try this:

dct = {
   1 : ['x', 'y'],
   2 : ['z'],
   3 : ['a']
}

print({key:val for val, keys in dct.items() for key in keys})

Output:

{'a': 3, 'x': 1, 'y': 1, 'z': 2}
dimay
  • 2,768
  • 1
  • 13
  • 22
0

You can try this.

d = {
1 :['x', 'y'],
2 :['z'],
3 :['a']
}

'''
{
   'x' : 1,
   'y' : 1,
   'z' : 2,
   'a' : 3
}
'''

d2 = {}


for k,v in d.items():
    for i in v:
        d2[i] = k


print(d2)

Output:

{'x': 1, 'y': 1, 'z': 2, 'a': 3}
[Finished in 0.2s]
Ice Bear
  • 2,676
  • 1
  • 8
  • 24