Search code examples
pythondictionarygetdictionary-comprehension

How to replace a dictionary values to keys of a dictionary and its keys to values


Does someone here know what I am doing wrong? I need to get a new dictionary from the keys, based in its values... For instance, if I have the following dictionary

dic = {'b':1, 'i':2, 'c':2, 'l':1, 'e':1, 'a':1}

I need to get a new dictionary which looks like this

newdic = {1:['b', 'l', 'e', 'a'],2:['i', 'c']

Or perhaps something else with a dictionary comprehension I have the following code which is not working properly

newdic={}

dic = {'b':1, 'i':2, 'c':2, 'l':1, 'e':1, 'a':1}
for letter in dic:
  newdic[dic.get(letter)] = [newdic.get(dic.get(letter), [])].append(letter)

print(newdic)

Solution

  • There is a way to do it using a dictionary comprehension but it is less readable:

    >>> {v: [k for k, v1 in dic.items() if v == v1] for v in dic.values()}
    {1: ['b', 'l', 'e', 'a'], 2: ['i', 'c']}