【问题标题】:How to switch values and keys with python dict?如何使用 python dict 切换值和键?
【发布时间】:2019-09-06 10:59:59
【问题描述】:

我的输入是:

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

我希望输出为:

{'Randy':['Input.txt','Output.txt'], 'Stan':['Code.py']}

基本上是这个switch key and values in a dict of lists的另一个方向

这是我尝试过的:

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

但它不起作用。我得到KeyError: 'Randy'

【问题讨论】:

标签: python dictionary


【解决方案1】:

这是一种简单的方法,我们遍历原始字典 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']}

【讨论】:

  • 你能解释一下吗?如果不使用更新方法,它是如何工作的?
  • 我会更好地指出我的问题,为什么 uasking for v not in dict 而不是 v not in dict.keys()
  • 那是一回事。
【解决方案2】:

您的代码存在一些问题。

让我们回顾一下:

  • 首先,您会遇到键错误,因为您尝试将值附加到不存在的键。为什么?因为在您之前的声明中,您向 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() 那样返回键值对
  • 如果键在那里,我们只需将当前值附加到它。
  • 在其他情况下,如果该键不存在,我们会向字典添加一个新键,但我们通过将其转换为列表来实现,否则将插入一个字符串作为值,而不是列表,您不会能够附加到它。

【讨论】:

    【解决方案3】:

    尝试使用defaultdict -

    from collections import defaultdict
    dictresult= defaultdict(list)
    for key,value in files.items():
         dictresult[value].append(key)
    

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

    【讨论】:

      【解决方案4】:

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

      喜欢

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

      【讨论】:

        【解决方案5】:
        output = {}
        for key, value in files.items():
            output[value] = output.get(value, []) + [key]
        
        print(output)
        # {'Randy':['Input.txt','Output.txt'], 'Stan':['Code.py']}
        

        【讨论】:

        • @Luis 如果有帮助也检查一下
        【解决方案6】:

        这里有两种方法可以做到。

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

        【讨论】:

          猜你喜欢
          • 2012-08-31
          • 1970-01-01
          • 2013-08-03
          • 2019-01-08
          • 2018-01-14
          • 2011-01-15
          • 2021-10-10
          • 2019-06-17
          相关资源
          最近更新 更多