• Dict字典的操作


    字典的操作

    1.字典新增键值对

    已存在内容的字典新增

    alient_0 = {"color":"green",position:10}
    alient_0["x_position"]= 1
    alient_0["y_position"] = 2
    print(alient_0)
    

    空字典新增

    alient_0 = {}
    alient_0["color"] = "green"
    alient_0["position"] = 10
    

    2. 字典修改键值对

    #修改字典键-值对
    alien_2 = {'color':'green','points':9}
    print("alient_2的颜色是:",alien_2['color'])
    alien_2['color'] = 'yellow'
    print("alient_2现在的颜色是:",alien_2['color'])
    

    3. 字典删除键值对


    del方法:删除指定的键值对

    pop方法:根据指定键,删除指定键值对

    popitem方法:删除最有一个键值对

    clear方法:清空所有的键值对

    alien_3 = {'color':'green','points':5}
    print("删除前",alien_3)
    del alien_3['points']
    print("删除后",alien_3)
    

    4. 查询内容

    alien_3 = {'color':'green','points':5}
    color = alien_3['color']
    

    遍历字典

    • 遍历key,value值

    user = {}
    user.items

    #遍历字典
    user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
    }
    for key,value in user_0.items
        print("
    Key:"+key)
        print("
    Value:"+value)
    

    5.遍历key值

    #遍历字典中的所有键
    favorite_languages = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
    }
    for name in favorite_languages.keys():
        print(name.title())
    

    6.遍历value值

    #遍历字典中的所有值
    favorite_languages = {
    'username': 'english',
    'first': 'chinese',
    'last': 'French',
    }
    for language in favorite_languages.values():
        print(language.title())
    

    字典嵌套

    • 列表里嵌套字典

    • 字典里嵌套列表

    #存储所点披萨的信息
    pizza = {
        'crust':'thick',
        'toppings':['mushrooms','extra cheese'],
        }
    
    print("披萨的配料有:",pizza['toppings'])
    
    • 字典里嵌套字典
    users = {
        '这里我最屌':{
            "姓":"小",
            "名":"明",
            "住址":"山卡拉"
        },
        '看谁最屌':{
            "姓":"小",
            "名":"红",
            "住址":"大都市"
        },
        }
    for username,userinfo in users.items():
        full_name = userinfo["姓"]+userinfo["名"]
        location = userinfo["住址"]
        print("用户名:
    "+username+"
    用户信息:
    姓名:"+full_name+" 住址:"+location)
    
  • 相关阅读:
    C# 获取文件名、无后缀文件名、扩展名
    navicat for oracle 导入xlsx文件提示无法打开xlsx文件
    复制的文件不能粘贴到远程的服务器上
    使用.bat 批量将部分文件迁移到新的路径下
    sql sever 查询用户所有的表和各个表数据量
    orecle 查询数量 union合并 的排序问题
    oracle 如何将带有,的一列分成多列
    java中selenium判断某个元素是否存在
    docker安装Ubuntu以及ssh连接
    Java8 将List<JavaBean>中某个属性取出来为单独的一个集合List<String>
  • 原文地址:https://www.cnblogs.com/yangsun/p/10163871.html
Copyright © 2020-2023  润新知