【问题标题】:Swapping values between two keys in a dictionary在字典中的两个键之间交换值
【发布时间】:2021-04-04 17:32:32
【问题描述】:
我正在尝试基于其他 dict 创建一个新的 dict,但是新的 dict 键值需要是不同键的值。
我试图做这样的事情:
dict1 = {'red: ['1'], 'blue': ['2']}
new_dict = dict1.copy()
new_dict.pop('blue')
new_dict.append['red':['1','2']]
我想它没有用,现在我在这里寻求帮助,TY!
【问题讨论】:
-
“没用”到底是什么意思?运行代码时会发生什么?你期望会发生什么?有什么错误吗?另请参阅How to Ask。
标签:
python
dictionary
key
【解决方案1】:
dict1 = {'red': ['1'], 'blue': ['2']}
new_dict = dict1.copy()
new_dict.pop('blue')
new_dict['red'] = ['1', '2']
print(dict1)
print(new_dict)
# OUTPUT
# {'red': ['1'], 'blue': ['2']}
# {'red': ['1', '2']}
你为什么要复制旧的字典?最终你会完全创建一个新的字典?
【解决方案2】:
当您调用 append 方法时,您使用“append[] ...”- 使用方括号这将不起作用!
你可以试试:
dict1 = {'red': ['1'], 'blue': ['2']}
new_dict = dict1.copy()
new_dict.pop('blue')
new_dict.update ={'red': ['1','2']}
这对字典很有用。
应该返回:
new_dict
Out: {'red': ['1', '2']}
您可以通过以下方式简单地将“蓝色”值添加到“红色”值:
dict1 = {'red': ['1'], 'blue': ['2']}
new_dict.update({'red': ['1', dict1.get('blue')]})
#OUTPUT
new_dict
# {'red': ['1', ['2']]}