如何用字典中的值交换键

2024-04-20 11:39:15 发布

您现在位置:Python中文网/ 问答频道 /正文

输出应包含原始字典中的所有键和值:

^{1}$

但是,当我尝试交换时,结果是:

^{pr2}$

我怎样才能解决这个问题?在


Tags: 字典pr2
3条回答

我来解释一下为什么你不能得到你想要的输出。在

我猜你的代码如下:

dicts = {1:'a', 2:'b', 3:'a', 4:'a'}
new_dicts = {v: k for k,v in dicts.items()}
print new_dicts

输出如下:

^{pr2}$

这是代码操作:

  • 步骤1:

    When {1:'a'} inserts new_dicts, the result is {'a':1}

  • 第二步:

    When {2:'b'} inserts new_dicts, the result is {'a':1', 'b':2}

  • 第三步:

    When {3:'a'} inserts new_dicts, the result is {'a':3, 'b':2} Because the a of key exists in dict, it causes to update value of corresponding key from 1 to 3.

  • 步骤4:

    When {4:'a'} inserts new_dicts, the result is {'a':3, 'b':4} Because the b of key exists in dict, it causes to update value of corresponding key from 2 to 4.

这就是为什么你得到输出,因为你不知道dict的特征

我不确定我是否完全回答了你的问题,因为这有点令人困惑。在上面的注释中,您显示您只想将1 : a的键/值反转为'a' : 1。在

您可能会发现collections模块很有用。在

import collections

d = collections.defaultdict(list)

dicts = {1:'a', 2:'b', 3:'a', 4:'a'}

for key, value in dicts.items():
    d[value].append(key)

然后尝试输出:

^{pr2}$

您可以添加已冲销的项目,然后删除以前的项目:

dicts.update(dict([(key, item) for item, key in dicts.items() if item in [1, 2]]))
del(dicts[1])
del(dicts[2])

^{pr2}$

相关问题 更多 >