我有以下Python词典:
{
"cat": 1,
"dog": 1,
"person": 2,
"bear": 2,
"bird": 3
}
我想使用字典理解将其转换为以下字典:
{
1 : ["cat", "dog"],
2 : ["person", "bear"],
3 : ["bird"]
}
我怎样才能在一个班轮里做这件事?
答案 0 :(得分:5)
这不是有效的,因为这不是如何使用dicts,但你可以做以下
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()}
答案 1 :(得分:0)
您可以将itertools.groupby
与单行使用:
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])}
输出:
{1: ['cat', 'dog'], 2: ['person', 'bear'], 3: ['bird']}
答案 2 :(得分:0)
>>> 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']}