如何交换字典中的备用键值对



我有一本字典dict1={ "K1":"V1","V2":"K2","K3":"V3","V4":"K4","K5":"V5"}。我想在python中交换可替换项的键/值对。输出如下所示:{ "K1":"V1","K2":"V2","K3":"V3","K4":"V4","K5":"V5"}

我正在尝试下面的代码。

def solution(dict1):
new_dict={}
for i in range(1,len(dict1)+1):
if i % 2 == 0:
for key, value in dict1.items():
new_dict[value] = [key]
else:
continue
return new_dict
dict1={ "K1":"V1","V2":"K2","K3":"V3","V4":"K4","K5":"V5"}
c=solution(dict1)
print(c)

但是这段代码是在交替字典中的所有元素。

试试这个:-

dict1 = {"K1": "V1", "V2": "K2", "K3": "V3", "V4": "K4", "K5": "V5"}

def solution(d):
rd = {}
for i, (k, v) in enumerate(d.items()):
if i % 2 != 0:
rd[v] = k
else:
rd[k] = v
return rd

print(solution(dict1))

我试了一下:

def solution(dict1):
new_dict={}
for key in dict1:
if 'K' in key:
new_dict[key]=dict1[key]
else:
new_dict[dict1[key]] = key
return new_dict

输出为:

{'K1': 'V1', 'K2': 'V2', 'K3': 'V3', 'K4': 'V4', 'K5': 'V5'}
k = 0
dict2 = {}
for key, value in dict1.items():
if k % 2 != 0:
dict2[value] = key
else:
dict2[key] = value
k = k+1

问题在行for key, value in dict1.items(): new_dict[value] = [key]您已经有了一个迭代器,所以当i是偶数时,您正在遍历整个列表。你只需要交换一个。我会这样做:

i = 0
for key in dict1:
i += 1
if i%2 == 0:
new_dict[dict1[key]] = key
else:
new_dict[key] = dict1[key]

在这里,迭代器i只检查它是偶数还是奇数,但它实际上并没有遍历dict对象。

最好创建一个新的字典副本,因为在迭代时直接从字典中添加/删除键值对会导致它的大小改变,从而导致运行时错误:RuntimeError: dictionary changed size during iteration。使用下面的代码来避免它:

dict1={ "K1":"V1","V2":"K2","K3":"V3","V4":"K4","K5":"V5"}
dict2 = {}
i = 0;
for key in dict1:
if i%2 == 1:
x = dict1[key]
dict2[x] = key
elif i%1 == 0:
dict2[key] = dict1[key]
i = i+1    
print(dict2)

可以使用字典推导式

dict1 = {"K1": "V1", "V2": "K2", "K3": "V3", "V4": "K4", "K5": "V5"}
dict2 = {
k if idx % 2 == 0 else v: v if idx % 2 == 0 else k
for idx, (k, v) in enumerate(dict1.items())
}

相关内容

  • 没有找到相关文章

最新更新