Reputation: 541
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?
Upvotes: 1
Views: 517
Reputation: 114
>>> a = {
... "cat": 1,
... "dog": 1,
... "person": 2,
... "bear": 2,
... "bird": 3
... }
>>>
>>> b = {}
>>> for key, value in a.items():
... if value not in b:
... b[value] = [key]
... else:
... b[value].append(key)
...
>>> print(b)
{1: ['cat', 'dog'], 2: ['person', 'bear'], 3: ['bird']}
Upvotes: 1
Reputation: 71451
You can use itertools.groupby
with a one-liner:
import itertools
d = {'person': 2, 'bird': 3, 'dog': 1, 'bear': 2, 'cat': 1}
new_d = {a:[i for i, _ in b] for a, b in itertools.groupby(sorted(d.items(), key=lambda x:x[-1]), key=lambda x:x[-1])}
Output:
{1: ['cat', 'dog'], 2: ['person', 'bear'], 3: ['bird']}
Upvotes: 0
Reputation: 3185
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()}
Upvotes: 4