输出应包含原始字典中的所有键和值:
dicts = {1: 'a', 2: 'b', 3: 'a', 4: 'a'}
但是,当我尝试交换它时,结果是:
{'a': 4, 'b': 2}
我该如何解决这个问题?
答案 0 :(得分:1)
不确定我是否完全回答了您的问题,因为它有点令人困惑。在上面的评论中,您表明您只想将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)
然后尝试输出:
>>> d
defaultdict(<type 'list'>, {'a': [1, 3, 4], 'b': [2]})
答案 1 :(得分:1)
让我解释为什么你无法获得你想要的输出。
我猜您的代码如下所示:
dicts = {1:'a', 2:'b', 3:'a', 4:'a'}
new_dicts = {v: k for k,v in dicts.items()}
print new_dicts
输出如下:
{'a': 4, 'b': 2}
这是代码操作:
步骤1:
当
{1:'a'}
插入new_dicts时,结果为{'a':1}
步骤2:
当
{2:'b'}
插入new_dicts时,结果为{'a':1', 'b':2}
步骤3:
当
{3:'a'}
插入new_dicts时,结果为{'a':3, 'b':2}
由于密钥中存在a
密钥,因此会导致将相应密钥的值从1
更新为3
。
步骤4:
当
{4:'a'}
插入new_dicts时,结果为{'a':3, 'b':4}
由于密钥中存在b
密钥,因此会导致将相应密钥的值从2
更新为4
。
这就是为什么你得到输出,因为你不知道字典的特征。
答案 2 :(得分:0)
您可以添加反转的项目,然后删除之前的项目:
dicts.update(dict([(key, item) for item, key in dicts.items() if item in [1, 2]]))
del(dicts[1])
del(dicts[2])
>>> dicts = {1:'a', 2:'b', 3:'a', 4:'a'}
>>> dicts.update(dict([(key, item) for item, key in dicts.items()[:2] if item in [1, 2]]))
>>> del(dicts[1])
>>> del(dicts[2])
>>> dicts
{'a': 1, 3: 'a', 4: 'a', 'b': 2}
>>>