Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将字典值替换为字典的键及其键替换为值_Python_Dictionary_Get_Dictionary Comprehension - Fatal编程技术网

Python 如何将字典值替换为字典的键及其键替换为值

Python 如何将字典值替换为字典的键及其键替换为值,python,dictionary,get,dictionary-comprehension,Python,Dictionary,Get,Dictionary Comprehension,这里有人知道我做错了什么吗? 我需要从键中获取一个新字典,基于它的值。。。 例如,如果我有以下字典 dic = {'b':1, 'i':2, 'c':2, 'l':1, 'e':1, 'a':1} 我需要买一本像这样的新字典 newdic = {1:['b', 'l', 'e', 'a'],2:['i', 'c'] 或者是有字典的其他东西 我有以下代码,它不能正常工作 newdic={} dic = {'b':1, 'i':2, 'c':2, 'l':1, 'e':1, 'a':1} fo

这里有人知道我做错了什么吗? 我需要从键中获取一个新字典,基于它的值。。。 例如,如果我有以下字典

dic = {'b':1, 'i':2, 'c':2, 'l':1, 'e':1, 'a':1}
我需要买一本像这样的新字典

newdic = {1:['b', 'l', 'e', 'a'],2:['i', 'c']
或者是有字典的其他东西 我有以下代码,它不能正常工作

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)

我们可以使用
collections.defaultdict
和一个简单的循环来反转数据

from collections import defaultdict

def reverse_dict(inp):
    output = defaultdict(list)
    for k, v in inp.items():
        output[v].append(k)
    return dict(output)

output = reverse_dict(dic)
print(output)
#{1: ['b', 'l', 'e', 'a'], 2: ['i', 'c']}

有一种方法可以通过字典理解来实现,但可读性较差:

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

下面是一个简单的方法:

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

for letter in dic:
    if dic[letter] not in newdic:
        newdic[dic[letter]] = []
    newdic[dic[letter]].append(letter)

print(newdic)

get方法的问题是您没有创建密钥。等式仅添加键,但不附加字母。

通过dict理解无法解决此问题,@PacketLoss?当然,如果是,但您必须添加一个附加循环(如接受的答案)。这在较大的数据集上可能较慢,并且可读性也较低。