Python快速入门(5):字典

1. 声明

fruit = {}

2. 添加

# 声明字典对象
fruit = {}
# 添加键值对
fruit["apple"] = 8
fruit["orange"] = 6
fruit["banana"] = 3

可以在声明时添加:

fruit = {
    "apple":8,
    "orange":6,
    "banana":3
}

3. 操作

  • 获取
print(fruit)
# 获取apple键对应的值
print(fruit["apple"])

--------
{'apple': 8, 'orange': 6, 'banana': 3}
8
  • 遍历所有的key
for key in fruit:
    print(key)
-------
apple
orange
banana

4. 案例:统计列表中水果出现的次数

fruit = ["apple","tomato","orange","grape","apple","orange","apple","tomato"]

fruit_dict = {}
# 遍历fruit列表
for item in fruit:
    # 判断fruit_dict字典中是否存在item键,存在则值加1,否则设置值为1
    if item in fruit_dict:
        fruit_dict[item] += 1
    else:
        fruit_dict[item] = 1
print(fruit_dict)
---------------
{'apple': 3, 'tomato': 2, 'orange': 2, 'grape': 1}

你可能感兴趣的:(Python快速入门(5):字典)