0

I am trying to sort out a dictionary so that the original can of the original dictionary can now be the key, and the original key will be grouped together by value as a list. Example shown below:

#original dict
dictionary = {"Hello":5,"Jacket":5,"Brackets":6,"Coat":3,"Comma":6,"quotation":3}

desired output:

Revised = {5:["Hello","Jacket"],6:["Brackets","Comma"],3:["Coat","quotation"]}

I tried the following:

def find():
    hello = dict()
    for item in dictionary:
        if dictionary[item] not in hello.values():
            hello[item] = item
        else:
            hello[item].append(item)
    return hello
hello = find()

However, I get a dictionary that is like this:

Wrong = {"Brackets":"Brackets","Coat":"Coat","Comma":"Comma","Hello":"Hello","Jacket":"Jacket","quotation":"quotation"}

What is the problem with by code, and how can I fix it? Thanks!!

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
  • Have you tried any debugging? – jonrsharpe Nov 23 '19 at 18:00
  • I have tried debugging, and it does seem like the dictionary[item] will actually give me the keys instead of values. I am not sure why as I thought this is the way to call on the value of the dictionary – JeyuLeoChou Nov 23 '19 at 18:03
  • `item` is a key in `dictionary`, `dictionary[item]` will be the corresponding value. Give a [mcve] to narrow this to the specific problem you can't solve. – jonrsharpe Nov 23 '19 at 18:04
  • You're basically after something like: `revised = {}` then `for k, v in dictionary.items(): revised.setdefault(v, []).append(k)`... or alternatives using `collections.defaultdict`... just trying to find you a canonical post that goes into more details – Jon Clements Nov 23 '19 at 18:05
  • 1
    Related, possible duplicate: https://stackoverflow.com/q/55706508/4014959 also see https://stackoverflow.com/q/483666/4014959 – PM 2Ring Nov 23 '19 at 18:15
  • 2
    Exact duplicate of [defaultdict example in the documentation](https://docs.python.org/3/library/collections.html#defaultdict-examples). – wim Nov 23 '19 at 18:29
  • You have to be careful of a few things when inverting a dict, as I mentioned [here](https://stackoverflow.com/a/43436972/4014959). – PM 2Ring Nov 23 '19 at 18:32

0 Answers0