字典翻转输出。Dcountry = {'中国':'北京','美国':'华盛顿','法国':'巴黎'},反转其中键值对输出。即输出:{'北京': '中国', '华盛顿': '美国', '巴黎': '法国'}
时间: 2023-07-29 15:07:16 浏览: 94
可以使用字典推导式来实现键值对的翻转输出,代码如下:
```python
Dcountry = {'中国': '北京', '美国': '华盛顿', '法国': '巴黎'}
Dcapital = {v: k for k, v in Dcountry.items()}
print(Dcapital)
```
输出结果为:`{'北京': '中国', '华盛顿': '美国', '巴黎': '法国'}`
相关问题
读入一个字典类型的字符串,反转其中的键值对输出。 即,读入字典key:value模式,输出value:key模式。
示例输入:
{"apple":"fruit","carrot":"vegetable","cat":"animal"}
示例输出:
{"fruit":"apple","vegetable":"carrot","animal":"cat"}
代码实现如下:
```python
import json
# 读入字符串作为字典
s = input()
d = json.loads(s)
# 反转键值对
d_reversed = {v: k for k, v in d.items()}
# 输出反转后的字典
print(json.dumps(d_reversed))
```
输入一个字典类型的字符串,反转其中键值对输出。即,读入字典key:value模式,输出value:key模式。
好的,可以使用以下代码实现:
```python
import ast
# 读入字典字符串
input_str = input("请输入字典字符串:")
# 将字符串转为字典
input_dict = ast.literal_eval(input_str)
# 反转键值对
output_dict = {v: k for k, v in input_dict.items()}
# 输出反转后的字典字符串
output_str = str(output_dict)
print(output_str)
```
示例输入:
```
请输入字典字符串:{'a': 1, 'b': 2, 'c': 3}
```
示例输出:
```
{1: 'a', 2: 'b', 3: 'c'}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)