dict = {} #空字典
字典中对键值得要求:
键:必须可哈希。 目前为止学到的可哈希的类型:int/bool/str/tuple;不可哈希的类型:list/set/dict。(集合)
值:任意类型。
info = { "age":12, "status":True, "name":"武沛齐", "data":None } data1 = info.get("name")
info = {"age":12, "status":True, "name":"wupeiqi","email":"xx@live.com"} data = info.keys()
info = {"age":12, "status":True, "name":"wupeiqi","email":"xx@live.com"} data = info.values()
info = {"age":12, "status":True, "name":"wupeiqi","email":"xx@live.com"} data = info.items()
data = { "name": "武沛齐", "email": 'xxx@live.com' } data.setdefault("age", 18)
info = {"age":12, "status":True} info.update( {"age":14,"name":"武沛齐"} ) # info中没有的键直接添加;有的键则更新值
info = {"age":12, "status":True,"name":"武沛齐"} data = info.pop("age") print(info) # {"status":True,"name":"武沛齐"} print(data) # 12
info = {"age":12, "status":True,"name":"武沛齐"} data = info.popitem() # ("name","武沛齐" ) print(info) # {"age":12, "status":True} print(data) # ("name","武沛齐")
并集
(Python3.9新加入)v1 = {"k1": 1, "k2": 2} v2 = {"k2": 22, "k3": 33} v3 = v1 | v2 print(v3) # {'k1': 1, 'k2': 22, 'k3': 33}
info = {"age":12, "status":True,"name":"武沛齐"} data = len(info)
键
,而列表和元组则是 0、1、2等数值
。info = { "age":12, "status":True, "name":"武沛齐"} print( info["age"] ) # 输出:12 print( info["name"] ) # 输出:武沛齐 print( info["status"] ) # 输出:True print( info["xxxx"] ) # 报错,通过键为索引去获取之后时,键不存在会报错(以后项目开发时建议使用get方法根据键去获取值) value = info.get("xxxxx") # None print(value)
info = {"age":12, "status":True,"name":"武沛齐"} info["gender"] = "男" # 增加键值对 info["age"] = "18" # 修改值 del info["age"] # 删除info字典中键为age的那个键值对(键不存在则报错)
info = {"age":12, "status":True,"name":"武沛齐"} for item in info: ----> for key,value in info.items(): # 循环键值对 for item in info.key(): # 循环键 for item in info.values(): # 循环值