如何在Python中使用字典?实例演示.

原创 快来打我* 2025-02-11 18:54 40阅读 0赞

在Python中,字典是一种可变容器模型,它通过键(key)存储和查找数据。以下是使用字典的实例:

  1. 创建一个空字典:

    1. my_dict = {}
  2. 使用键添加元素到字典:

    1. my_dict['apple'] = 1
    2. my_dict['banana'] = 2

    现在,my_dict 字典包含以下内容:

  1. {
  2. 'apple': 1,
  3. 'banana': 2
  4. }
  1. 使用键获取元素:
    ```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中使用字典的基本操作。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,40人围观)

还没有评论,来说两句吧...

相关阅读