如何使用python dict切换值和键? [英] How to switch values and keys with python dict?

查看:91
本文介绍了如何使用python dict切换值和键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输入是:

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'

But it doesn't work. I get KeyError: 'Randy'

推荐答案

这是一种简单的方法,我们迭代原始字典fileskeysvalues并为每个值创建列表以将所有键附加到该值对应于该值.

Here's simple approach where we iterate over keys and values of your original dict files and create list for each value to append to it all keys corresponding to that value.

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

这篇关于如何使用python dict切换值和键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆