Search code examples
pythondictionarydictionary-comprehension

Converting Python dictionary using dictionary comprehension


I have the following Python dictionary:

{
 "cat": 1,
 "dog": 1,
 "person": 2,
 "bear": 2,
 "bird": 3
}

I would like to use dictionary comprehensions to convert it to the following dictionary:

{
 1 : ["cat", "dog"],
 2 : ["person", "bear"],
 3 : ["bird"]
}

How can I go about doing this in a one liner?


Solution

  • This is not efficient as this is not how dicts are intended to be used, but you can do the following

    d = {"cat": 1, "dog": 1, "person": 2, "bear": 2, "bird": 3}
    
    new = {v: [i[0] for i in d.items() if i[1] == v] for v in d.values()}