-2

I've got such a dict:

{'ab20': 'London', 'kn44': 'London', 'fe85': 'London', 'fg487': 'Paris', 'fe32': 'Paris'...}

It makes much more sence, if I change it into something like this:

{'London': ['ab20', 'kn44',  'fe85'], 'Paris': ['fg487', 'fe32'] ... }

What is the most efficient way to do this?

cs95
  • 379,657
  • 97
  • 704
  • 746
anastasiiia
  • 189
  • 2
  • 12

1 Answers1

3

Use a defaultdict:

d  ={'ab20': 'London', 'kn44': 'London', 'fe85': 'London', 'fg487': 'Paris', 'fe32': 'Paris'}
from collections import defaultdict

result = defaultdict(list)
for key, val in d.items():
    result[val].append(key)
print(result)

Output:

{'London': ['ab20', 'kn44', 'fe85'], 'Paris': ['fg487', 'fe32']}