python 基础7-字典
字典 dict
主要方法:
keys() ,values(),items() ,get() ,update()
基本结构:
info = {
"k1":18,
"k2":19
}
# 字典的value可以是任意值;布尔值、列表、字典不能作为字典的key
#字典无序
info = {
"k1":18,
"1":True,
"k3":[11,[],(),22,33,{
"kk1":"vv1",
"kk2":"vv2",
"kk3":(8,9),
}],
"k4":("q","w",55,66),
True:"ww"
}
print(info)
# 通过索引查找到指定元素
v = info["k3"]
print(v)
v1 = info["k3"][5]["kk1"]
print(v1)
# 删除字典元素
#del info["k1"]
del info["k3"][5]["kk1"]
print(info)
for item in info:
print(item)
# ==
for item in info.keys():
print(item)
for item in info.values():
print(item)
for item in info.keys():
print(item,info[item])
# ==
for k,v in info.items():
print(k,v)
#根据序列 创建字典,并制定统一的值
v = dict.fromkeys(["k1","k2","k3"],123)
print(v)
info = {
"k1":"v1",
"k2":"v2"
}
v = info.get("k2",123)
print(v)
# 可指定删除 键值对
info.pop("k3",123)
print(info)
# 随机删除 键值对
v = info.popitem()
print(info,v)
# 设置值
# 已存在,不设置,获取当前key对应的值
# 不存在,设置,获取当前Key对应的值
v = info.setdefault("k3",123)
print(info,v)
# 更新
info.update({"k1","234"})
print(info)