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.
我来解释一下为什么你不能得到你想要的输出。在
我猜你的代码如下:
输出如下:
^{pr2}$这是代码操作:
步骤1:
第二步:
第三步:
步骤4:
这就是为什么你得到输出,因为你不知道dict的特征
我不确定我是否完全回答了你的问题,因为这有点令人困惑。在上面的注释中,您显示您只想将
1 : a
的键/值反转为'a' : 1
。在您可能会发现collections模块很有用。在
然后尝试输出:
^{pr2}$您可以添加已冲销的项目,然后删除以前的项目:
^{pr2}$
相关问题 更多 >
编程相关推荐