Python基础:字典的创建和使用
在Python中,字典(Dictionary)是一种可变容器模型,且其每个键值对都是相互独立的。
使用键值对创建字典
dict_example = {
“Name”: “Alice”,
“Age”: 25,
“City”: “New York”
}
字典还可以通过列表初始化的方式创建
list_to_dict = dict([(‘Key1’, ‘Value1’), (‘Key2’, ‘Value2’)]))
print(“Empty Dictionary:”, empty_dict)
print(“Example Dictionary:”, dict_example)
print(“Dictionary Created Using List:”, list_to_dict)
```
- 使用字典:
- 获取键对应的值:
value = dict_example['Name']
- 检查键是否存在:
if 'Age' in dict_example: print(dict_example['Age'])
- 更新或添加键值对:
dict_example['City']'] = 'San Francisco'
以上就是在Python中创建和使用字典的基本操作。
还没有评论,来说两句吧...