资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Python之字典使用

字典的增删改查使用

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])

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

当前标题:Python之字典使用
网页链接:http://cdkjz.cn/article/pjcdsh.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220