设计python将以下字典翻转dt1({"BJ": "CHN","CA": "US", "SH":"CHN", "TW": "CHN","NY":"US", "ON": "CA"})
时间: 2023-09-15 13:21:24 浏览: 156
在Python中实现字典反转案例
可以使用以下代码将字典翻转:
dt1 = {"BJ": "CHN","CA": "US", "SH":"CHN", "TW": "CHN","NY":"US", "ON": "CA"}
dt2 = {}
for key, value in dt1.items():
dt2.setdefault(value, []).append(key)
print(dt2) # 输出结果:{'CHN': ['BJ', 'SH', 'TW'], 'US': ['CA', 'NY'], 'CA': ['ON']}
阅读全文