成都网站建设设计

将想法与焦点和您一起共享

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://chengdu.cdxwcx.cn/article/pjcdsh.html