python字典翻转教学头歌答案
时间: 2025-01-08 22:20:46 浏览: 78
### Python 字典翻转 示例代码教程
#### 使用字典推导式进行简单翻转
当处理简单的键值对且这些值都是独一无二的时候,可以利用字典推导式轻松完成字典的反转操作。这种方式简洁明了。
```python
original_dict = {'apple': 'fruit', 'carrot': 'vegetable', 'banana': 'fruit'}
inverted_dict = {value: key for key, value in original_dict.items()}
print(inverted_dict) # 输出:{'fruit': 'banana', 'vegetable': 'carrot'}
```
注意,在这个例子中最后的结果只保留了一个`'fruit'`对应的键 `'banana'`,因为字典不允许重复的键[^3]。
#### 处理非唯一值的情况
如果原字典中有多个相同的值,则上述方法会导致部分数据丢失。为了保存所有的映射关系,可以创建一个多值字典,即让新的字典中的每一个键对应一个列表形式的值。
```python
def invert_dictionary_with_duplicates(dict_input):
inverted = {}
for key, value in dict_input.items():
if value not in inverted:
inverted[value] = [key]
else:
inverted[value].append(key)
return inverted
example_dict = {'a': 1, 'b': 2, 'c': 1}
result = invert_dictionary_with_duplicates(example_dict)
print(result) # 输出:{1: ['a', 'c'], 2: ['b']}
```
此函数遍历给定字典的所有项,并构建一个新的字典,其中每个新加入的条目都会被检查是否存在相同值;如果有则追加到现有列表里而不是覆盖原有记录[^5]。
#### 输入验证与异常处理
考虑到实际应用环境中可能遇到的各种情况,比如用户输入错误等问题,应该增加必要的输入校验逻辑以及异常捕获机制来提高程序健壮性。
```python
try:
user_input = eval(input("请输入要翻转的字典(格式如:{'name':'张三','age':20}): "))
if isinstance(user_input, dict):
result = {v: k for k, v in user_input.items()}
print(f"翻转后的字典为:\n{result}")
else:
raise ValueError("输入不是一个有效的字典")
except Exception as e:
print(f"发生错误: {e}")
```
这段脚本首先尝试评估用户的输入是否是一个合法的Python表达式(这里假设是以字符串形式给出),接着判断其类型是不是字典,如果不是就抛出异常提示用户重新输入正确的格式[^2]。
阅读全文
相关推荐

















