-4

I looked at the other invert question, but that one does not have a dictionary with lists so that doesn't help me out.

So I have a dictionary and basically I want to invert it. So the keys become the values and the values become the keys. For example if I have: {'Sun' : ['hot', 'yellow'], 'Car': ['yellow'], 'Fire': ['hot']}, it should return: {'yellow': ['Sun', 'Car'], 'hot': ['Sun', 'Fire']}

I have tried just getting the key values but I don't know how to get them into the dictionary and assigning the key values to them. I would appreciate any help but using the most basic methods if possible Thanks

lankup90
  • 11
  • 2

1 Answers1

0
from collections import OrderedDict

def invert(d):
    inversion = {}
    for key, vals in d.items():
        for val in vals:
            lst = inversion.get(val, None)
            if lst is None:
                lst = []
                inversion[val] = lst
            lst.append(key)
    for lst in inversion.values():
        lst.sort()
    return OrderedDict(sorted(inversion.items()))

print(invert({'Sun' : ['hot', 'yellow'], 'Car': ['yellow'], 'Fire': ['hot']}))
#-> OrderedDict([('hot', ['Fire', 'Sun']), ('yellow', ['Car', 'Sun'])])
Dylon
  • 1,730
  • 15
  • 14
  • Thank you. Just wanted to ask how would you sort these as you can't just use .sort() – lankup90 Nov 30 '19 at 22:23
  • @lankup90 from python 3.7 dicts are insertion sorted. If you mean the lists, you can just use `.sort()`... – Tomerikoo Nov 30 '19 at 22:26
  • If you want the keys in your dictionary sorted, you should use an OrderedDict; if you want the values in the inverted indices sorted, you should add a post-processing step to sort them. I'll update the example to show you how. – Dylon Nov 30 '19 at 22:27
  • @Dylon Thanks so much! I just needed the lists sorted and I got it thanks for your help. – lankup90 Nov 30 '19 at 23:44
  • This logic is overly complicated -- while you're grabbing `OrderedDict` from collections, grab `defaultdict` as well and initilize `inversion = defaultdict(list)`. Then you can just assume that the values in `inversion` exist and you can append onto them: `inversion[val].append(key)` without *any* testing beforehand. And while you're at it: `map(list.sort, inversion.values())` instead of your loop. – cdlane Dec 01 '19 at 07:32