Python字典解析与使用教程
Python字典解析与使用教程
一、什么是字典?
在Python中,字典是一种可变容器模型。它类似于现实生活中的地图,键(Key)作为地址,值(Value)则是对应的内容。
二、字典的创建
- 直接赋值创建字典:
dict_example = {'name': 'John', 'age': 30}
- 使用内置函数创建字典:
dict_from_list = dict([('key1', 'value1'), ('key2', 'value2')]))
三、字典的访问
- 通过键获取值:
print(dict_example['name']) # 输出: John
- 检查键是否存在:
if 'age' in dict_example:
print(dict_example['age']) # 输出: 30
else:
print("Age is not present in the dictionary")
四、字典的修改和删除
- 修改值:
dict_example['age'] = 35
print(dict_example) # 输出: {'name': 'John', 'age': 35}
- 删除键值对:
del dict_example['age']
print(dict_example) # 输出: {'name': 'John'}
以上就是Python字典的创建、访问、修改和删除的基本操作。在实际编程中,字典经常用于存储和管理不同类型的数据。
还没有评论,来说两句吧...