美文网首页
Python快速入门(5):字典

Python快速入门(5):字典

作者: 大锅烩菜 | 来源:发表于2018-09-01 16:17 被阅读0次

    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):字典

          本文链接:https://www.haomeiwen.com/subject/erruwftx.html