如何使用python dict切换值和键?

如何使用python dict切换值和键?,python,dictionary,Python,Dictionary,我的意见是: 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]

我的意见是:

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)
但它不起作用。我得到
键错误:“Randy”
尝试使用-


这将假定字典中的每个项中都有一个空列表,因此追加不会失败。这里有一个简单的方法,我们迭代原始dict
文件的
键和
值,并为每个值创建列表,将与该值对应的所有键追加到该列表中

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

您可以检查dictresult中是否存在作为键的值


您的代码有一些问题

让我们回顾一下:

  • 首先,您将得到key error,因为您试图向不存在的key追加一个值。为什么?因为在前面的语句中,您向dict[key]添加了一个值,现在您正试图访问/追加dict[value]

    dictresult[key]=value
    
  • 您正在为新生成的键赋值,而不进行任何检查。每个新值都将覆盖它

    dictresult[value].append(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()不同的键值对
  • 如果键在那里,我们只需将当前值附加到它
  • 在另一种情况下,当该键不存在时,我们将一个新键添加到字典中,但我们通过将其强制转换到列表中来实现,否则一个字符串将作为值而不是列表插入,并且您将无法附加到它

    • 以下是两种方法

      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!!!")
      

      你能解释一下吗?如果不使用更新方法,它是如何工作的?我会更好地指出我的问题,为什么在dict中不使用v而不是在dict中使用v。keys()这是同一件事。@Luis也检查一下这是否有帮助
      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']}
      
      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!!!")