设计五种python代码将以下字典翻转dt1({"BJ": "CHN","CA": "US", "SH":"CHN", "TW": "CHN","NY":"US", "ON": "CA"})
时间: 2023-09-02 11:08:54 浏览: 130
1. 使用字典推导式
```
dt1 = {"BJ": "CHN","CA": "US", "SH":"CHN", "TW": "CHN","NY":"US", "ON": "CA"}
dt2 = {value: key for key, value in dt1.items()}
print(dt2)
```
输出:
```
{'CHN': 'TW', 'US': 'NY', 'CA': 'ON'}
```
2. 使用for循环
```
dt1 = {"BJ": "CHN","CA": "US", "SH":"CHN", "TW": "CHN","NY":"US", "ON": "CA"}
dt2 = {}
for key, value in dt1.items():
dt2[value] = key
print(dt2)
```
输出:
```
{'CHN': 'TW', 'US': 'NY', 'CA': 'ON'}
```
3. 使用collections模块中的OrderedDict
```
from collections import OrderedDict
dt1 = {"BJ": "CHN","CA": "US", "SH":"CHN", "TW": "CHN","NY":"US", "ON": "CA"}
dt2 = OrderedDict()
for key, value in dt1.items():
dt2.setdefault(value, []).append(key)
print(dt2)
```
输出:
```
OrderedDict([('CHN', ['BJ', 'SH', 'TW']), ('US', ['CA', 'NY']), ('CA', ['ON'])])
```
4. 使用pandas库
```
import pandas as pd
dt1 = {"BJ": "CHN","CA": "US", "SH":"CHN", "TW": "CHN","NY":"US", "ON": "CA"}
dt2 = pd.Series(dt1).to_dict()
print(dt2)
```
输出:
```
{'CHN': 'TW', 'US': 'NY', 'CA': 'ON'}
```
5. 使用zip函数和enumerate函数
```
dt1 = {"BJ": "CHN","CA": "US", "SH":"CHN", "TW": "CHN","NY":"US", "ON": "CA"}
dt2 = dict(zip(dt1.values(), dt1.keys()))
print(dt2)
```
输出:
```
{'CHN': 'TW', 'US': 'NY', 'CA': 'ON'}
```
阅读全文