1

I have dictionaries like :

Letters_value = dict.fromkeys(['a', 'b', 'c'], 2)
Letters_value.update(dict.fromkeys(['d','e', 'f'], 3))
Letters_value.update(dict.fromkeys(['g','h', 'i'], 4))
Letters_value.update(dict.fromkeys(['j','k', 'l'], 5))
Letters_value.update(dict.fromkeys(['m','n', 'o'], 6))
Letters_value.update(dict.fromkeys(['p','q', 'r','s'], 7))
Letters_value.update(dict.fromkeys(['t','u', 'v'],8 ))
Letters_value.update(dict.fromkeys(['w','x', 'y','z'],9 ))
Letters_value.update(dict.fromkeys(['-'],'' ))

Is there a nice way to reverse them so that I get something like :

{'2':['a','b','c'], '3':['d','e','f'].... }
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Remi-007
  • 145
  • 1
  • 11

2 Answers2

1

Using collections.defaultdict

Ex:

from collections import defaultdict


Letters_value = dict.fromkeys(['a', 'b', 'c'], 2)
Letters_value.update(dict.fromkeys(['d','e', 'f'], 3))
Letters_value.update(dict.fromkeys(['g','h', 'i'], 4))
Letters_value.update(dict.fromkeys(['j','k', 'l'], 5))
Letters_value.update(dict.fromkeys(['m','n', 'o'], 6))
Letters_value.update(dict.fromkeys(['p','q', 'r','s'], 7))
Letters_value.update(dict.fromkeys(['t','u', 'v'],8 ))
Letters_value.update(dict.fromkeys(['w','x', 'y','z'],9 ))
Letters_value.update(dict.fromkeys(['-'],'' ))

res = defaultdict(list)
for k, v in Letters_value.items():
    res[v].append(k)
print(res)

Output:

defaultdict(<type 'list'>, {'': ['-'], 2: ['a', 'c', 'b'], 3: ['e', 'd', 'f'], 4: ['g', 'i', 'h'], 5: ['k', 'j', 'l'], 6: ['m', 'o', 'n'], 7: ['q', 'p', 's', 'r'], 8: ['u', 't', 'v'], 9: ['w', 'y', 'x', 'z']})
Rakesh
  • 81,458
  • 17
  • 76
  • 113
-1

We can swap the positions of key-value pair in a dictionary by the following line:

dict((v, k) for k, v in Letters_value.items())

or you can also use,

{v: k for k, v in Letters_value.items()}

I hope it can help you. :-)

Sukjun Kim
  • 187
  • 1
  • 5
  • This does not work since most of the information would be lost (there are multiple identical values in the original dictionary, but keys need to be unique). – Tim Pietzcker Sep 05 '18 at 07:42
  • @TimPietzcker Yes, I know. I have only focused on the methodology for reversing/inverting a mapping of a dictionary data. We have to check whether original values in a dictionary are unique of values of a dictionary prior to reversing/inverting a mapping. I answered it with the assumption that the example above(`Letters_value`) already meets the condition of uniqueness. – Sukjun Kim Sep 05 '18 at 07:56
  • @TimPietzcker Thank you for letting me know. I missed the point of the question. I agree with your comment. It became a chance to think about the loss of information. :) – Sukjun Kim Sep 05 '18 at 15:27