简体   繁体   中英

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?

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()}

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']}
>>> 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']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM