如何使用Python字典交换键和值?

4

我的输入是:

files = {
    'Input.txt': 'Randy',
    'Code.py': 'Stan',
    'Output.txt': 'Randy'
} 

我希望得到以下输出结果:
{'Randy':['Input.txt','Output.txt'], 'Stan':['Code.py']}

基本上这是一个 将字典中的键和值互换 的问题。
这是我尝试过的方法:
dictresult= {}
for key,value in files.items():
     dictresult[key]=value
     dictresult[value].append(key)

但它不起作用。我收到了KeyError:'Randy'的错误。


可能是在Python中交换字典中的键和值的重复问题。 - juankysmith
6个回答

5
这是一个简单的方法,我们遍历您原始字典fileskeysvalues,为每个值创建一个列表,并将对应于该值的所有键附加到该列表中。
files = {
    'Input.txt': 'Randy',
    'Code.py': 'Stan',
    'Output.txt': 'Randy'
}

dictresult= {}

for k, v in files.items():
    if v not in dictresult:
        dictresult[v] = [k]
    else:
        dictresult[v].append(k)

print(dictresult) # -> {'Randy': ['Output.txt', 'Input.txt'], 'Stan': ['Code.py']}

你能稍微解释一下吗?它是如何在不使用update方法的情况下工作的? - Luis
我会更明确地指出我的问题,为什么你要询问v不在字典中而不是v不在dict.keys()中? - Luis
那是同样的事情。 - Filip Młynarski

4

你的代码有几个问题。

让我们来看一下:

  • Firstly, you're getting key error because you're trying to append a value to key that doesn't exist. Why? because in you earlier statement you added a value to dict[key] and now you're trying to access/append dict[value].

    dictresult[key]=value
    
  • You're assigning value to newly generated key, without any check. every new value will overwrite it.

    dictresult[value].append(key)
    
  • Then you're trying to append a new value to a string using a wrong key.
你可以通过以下代码实现你想要的功能:
d = {}
for key,value in files.items():
if value in d:
    d[value].append(key)
else:
    d[value] = [key]
print(d)

它将输出:
{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}

如何/为什么起作用?

让我们回顾一下:

  • if条件语句检查字典中是否已经存在该键。当遍历字典时,它只返回它的键,而不是键值对,与dict.items()不同。
  • 如果该键已经存在,则将当前值简单地附加到该键上。
  • 在其他情况下,如果该键不存在,则将一个新的键添加到字典中,但是需要使用list类型进行转换,否则字符串将被插入为值,而不是列表,并且您将无法追加它。

1
尝试使用 defaultdict -
from collections import defaultdict
dictresult= defaultdict(list)
for key,value in files.items():
     dictresult[value].append(key)

这将假设字典中的每个项都有一个空列表,因此追加操作不会失败。

0

你可以检查字典 dictresult 中是否存在以某个值为键的项

例如:

dictresult= {}
for key,value in files.items():
     if not value in dictresult: dictresult [value]=[]
     dictresult[value].append(key)

0
output = {}
for key, value in files.items():
    output[value] = output.get(value, []) + [key]

print(output)
# {'Randy':['Input.txt','Output.txt'], 'Stan':['Code.py']}

@Luis,也请检查一下这个是否有帮助。 - Anand Tripathi

0

以下是两种实现方法。

from collections import defaultdict


files = {"Input.txt": "Randy", "Code.py": "Stan", "Output.txt": "Randy"}    
expected = {"Randy": ["Input.txt", "Output.txt"], "Stan": ["Code.py"]}


# 1st method. Using defaultdict
inverted_dict = defaultdict(list)
{inverted_dict[v].append(k) for k, v in files.items()}
assert inverted_dict == expected, "1st method"

# 2nd method. Using regular dict
inverted_dict = dict()
for key, value in files.items():
    inverted_dict.setdefault(value, list()).append(key)
assert inverted_dict == expected, "2nd method"

print("PASSED!!!")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接