如何在Python中使用字典?实例演示.
在Python中,字典是一种可变容器模型,它通过键(key)存储和查找数据。以下是使用字典的实例:
创建一个空字典:
my_dict = {}
使用键添加元素到字典:
my_dict['apple'] = 1
my_dict['banana'] = 2
现在,
my_dict
字典包含以下内容:
{
'apple': 1,
'banana': 2
}
- 使用键获取元素:
```python
fruit_quantity = my_dict[‘apple’]
print(fruit_quantity) # Output: 1
new_quantity = my_dict.get(‘orange’, 0))
print(new_quantity) # Output: 0 (since ‘orange’ is not in the dictionary)
```
以上就是在Python中使用字典的基本操作。
还没有评论,来说两句吧...