# Python中字典的键要求必须是不可变类型,例如:数字、字符串、元组等。列表和字典等可变类型不能作为字典的键。
# 示例1:使用字符串作为键
dict1 = {'name': 'Alice', 'age': 25}
print(dict1)
# 示例2:使用数字作为键
dict2 = {1: 'apple', 2: 'banana'}
print(dict2)
# 示例3:使用元组作为键
dict3 = {(1, 2): 'coordinate'}
print(dict3)
# 示例4:尝试使用列表作为键(会抛出TypeError)
try:
dict4 = {[1, 2]: 'list_key'} # 这将引发TypeError
except TypeError as e:
print(f"Error: {e}")
# 示例5:尝试使用字典作为键(会抛出TypeError)
try:
dict5 = {{'a': 1}: 'dict_key'} # 这将引发TypeError
except TypeError as e:
print(f"Error: {e}")
上一篇:python 字符替换
下一篇:redis python
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站