Lesson 2#06 字典

字典是一种key:value,的数据类型,使用时就像我们上学用的字典,通过key查找对应的value值

特性:

·key:value结构

·key必须是可hash的,key必须唯一

·value可以是任意多个值、可修改、可以不唯一

·无序的,因为没有索引,所以没有顺序

·查找速度快

info = {
    "suyp":18,
    "lirs":"nan",
    "liuzhen":["it",19],
    "machao":("nan",20),
    "zhoubin":{
        "IT":"开发工程师",
        "age":18
    }
}
#key必须唯一
#value可以是任意值,例如:数字、字符串、列表、元组、字典
print(info["suyp"])
print(info["liuzhen"])
print(info["machao"])
print(info["zhoubin"])
print(info["zhoubin"]["IT"])#字典嵌套的查询
#执行结果
>>>18
>>>['it', 19]
>>>('nan', 20)
>>>{'IT': '开发工程师', 'age': 18}
>>>开发工程师

字典修改:

info = {
    "suyp":18,
    "lirs":"nan",
    "liuzhen":["it",19],
    "machao":("nan",20),
    "zhoubin":{
        "IT":"开发工程师",
        "age":18
    }
}
info["suyp"]="SUYP" #修改value
info["liuzhen"][1]=20 #修改value:列表
info["zhoubin"]["IT"]="设计师"#修改value:字典嵌套
print(info)
#执行结果
>>>{'suyp': 'SUYP', 'lirs': 'nan', 'liuzhen': ['it', 20], 'machao': ('nan', 20), 'zhoubin': {'IT': '设计师', 'age': 18}}

字典的增加

info = {
    "suyp":18,
    "lirs":"nan",
    "liuzhen":["it",19],
    "machao":("nan",20),
    "zhoubin":{
        "IT":"开发工程师",
        "age":18
    }
}
info["wanggx"]=18 # 增加 [key] = value

字典的查找

info = {
    "suyp":18,
    "lirs":"nan",
    "liuzhen":["it",19],
    "machao":("nan",20),
    "zhoubin":{
        "IT":"开发工程师",
        "age":18
    }
}

print("suyp"in info) #判断key是否在info中,有则返回True,没有返回False
print(info.get("suyp"))#如果key存在info中,返回value,没有返回None

字典的删除

info = {
    "suyp":18,
    "lirs":"nan",
    "liuzhen":["it",19],
    "machao":("nan",20),
    "zhoubin":{
        "IT":"开发工程师",
        "age":18
    }
}
print(info.pop("suyp")) #删除一个key并返回value
print(info.popitem())#随机删除一个key并返回value
print(info.clear())#清空字典
info = {
    "suyp":18,
    "lirs":"nan",
    "liuzhen":["it",19],
    "machao":("nan",20),
    "zhoubin":{
        "IT":"开发工程师",
        "age":18
    }
}
del info["suyp"] #删除指定的key
print(info)

多级字典的嵌套

 

posted @ 2018-03-26 21:27  WudTime  阅读(143)  评论(0编辑  收藏  举报