zoukankan      html  css  js  c++  java
  • 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)
    
  • 相关阅读:
    Makoto and a Blackboard CodeForces
    Bash Plays with Functions CodeForces
    2016 计蒜之道 初赛 第一场 D 青云的机房组网方案 (虚树)
    常用数论函数求和公式
    AC日记——元素查找 codevs 1230
    AC日记——鬼谷子的钱袋 codevs 2998
    AC日记——接龙游戏 codevs 1051
    AC日记——逆波兰表达式 openjudge 3.3 1696
    AC日记——欧几里得的游戏 洛谷 P1290
    AC日记——刺激 codevs 1958
  • 原文地址:https://www.cnblogs.com/yangsun/p/10163871.html
Copyright © 2011-2022 走看看