温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python 之 字典使用

发布时间:2020-06-07 07:40:31 来源:网络 阅读:226 作者:wx592bc92b285c7 栏目:编程语言

字典的增删改查使用

1、增加

info = {
    "person1":"大s",
    "person2":"小s",
    "person3":"小3",
    "person4":"小4"
}
info["person5"]="小5"  
info = {
    "广东" : {
        "深圳":["罗湖", "福田", "南山"],
        "广州":["天河", "番禺", "白云"],
    },
    "浙江" : {
        "杭州":["西湖","下城","上城"],
        "温州":["龙湾","瑞安"],
    },
    "江苏" : {
        "苏州":["沧浪","平江","吴中"],
        "南京":["白下","浦口","你好"],
    }
}
info["湖南"]={"长沙":[1,2,3]}
#增加了一个key为湖南的内容

2、删除

info = {
    "person1":"大s",
    "person2":"小s",
    "person3":"小3",
    "person4":"小4"
#---------key----value------
}

del info["person4"]

3、修改

info = {
    "person1":"大s",
    "person2":"小2",
    "person3":"小3",
    "person4":"小4"
#---------key----value------
}
info["person1"] = "大1"
info = {
    "广东" : {
        "深圳":["罗湖", "福田", "南山"],
        "广州":["天河", "番禺", "白云"],
    },
    "浙江" : {
        "杭州":["西湖","下城","上城"],
        "温州":["龙湾","瑞安"],
    },
    "江苏" : {
        "苏州":["沧浪","平江","吴中"],
        "南京":["白下","浦口","你好"],
    }
}

info["江苏"]["南京"] = [1,2,3]
print(info["江苏"]["南京"])
#结果:[1,2,3]

4、查询

info = {
    "person1":"大s",
    "person2":"小2",
    "person3":"小3",
    "person4":"小4"
#---------key----value------
}
print(info.get("person1"))   #此方法如果主键不存在,也不会报错
print(info["person1"])         #此方法跟上面一样,但如果主键不存在,系统报错
info = {
    "广东" : {
        "深圳":["罗湖", "福田", "南山"],
        "广州":["天河", "番禺", "白云"],
    },
    "浙江" : {
        "杭州":["西湖","下城","上城"],
        "温州":["龙湾","瑞安"],
    },
    "江苏" : {
        "苏州":["沧浪","平江","吴中"],
        "南京":["白下","浦口","你好"],
    }
}

print(info["江苏"])
#结果:{'苏州': ['沧浪', '平江', '吴中'], '南京': ['白下', '浦口', '你好']}
print(info["江苏"]["苏州"])
#结果:['沧浪', '平江', '吴中']

5、字典for循环

info = {
    "广东" : {
        "深圳":["罗湖", "福田", "南山"],
        "广州":["天河", "番禺", "白云"],
    },
    "浙江" : {
        "杭州":["西湖","下城","上城"],
        "温州":["龙湾","瑞安"],
    },
    "江苏" : {
        "苏州":["沧浪","平江","吴中"],
        "南京":["白下","浦口","你好"],
    }
}

for i in info:
    print(i,info[i])

#结果:
广东 {'深圳': ['罗湖', '福田', '南山'], '广州': ['天河', '番禺', '白云']}
浙江 {'杭州': ['西湖', '下城', '上城'], '温州': ['龙湾', '瑞安']}
江苏 {'苏州': ['沧浪', '平江', '吴中'], '南京': ['白下', '浦口', '你好']}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI