关于Python字典的常见操作案例
在Python中,字典是一种可变容器模型,类似于数组,但键是不可变的。以下是一些常见的字典操作:
创建字典:
dict1 = {'name': 'Alice', 'age': 25}
访问元素(键值对):
print(dict1['name']) # 输出: Alice
修改元素:
dict1['age'] = 26
print(dict1) # 输出: {'name': 'Alice', 'age': 26}
删除元素:
del dict1['age']
print(dict1) # 输出: {'name': 'Alice'}
判断键是否存在:
if 'name' in dict1:
print(f"Name exists: {dict1['name']}]")
else:
print("Name does not exist.")
以上就是Python字典的一些常见操作案例。
还没有评论,来说两句吧...