python之字典

字典是以键值对的方式存储
字典的定义:
1、通过{}
2、通过dict 进行转换,如:d1=dict(list1)

字典的相关函数:
(1)添加键值()字典不存在的键
d={"name":"zs","age":18}
d["sex"]="女"
print(d)
image
(2)添加键值()字典已存在的键,新添加的优先级会更高
d={"name":"zs","age":18}
d["age"]="20"
print(d)
image

(3)keys 获取所有的键
d={"name":"zs","age":18}
print(d.keys())
image
(4) values   获取所有的值
d={"name":"zs","age":18}
print(d.values())
image
(5)1、for循环遍历字典
d={"name":"zs","age":18}
for  i in  d:
    print(i)
image
2、遍历字典中的键和值
d={"name":"zs","age":18}
for  i in  d:
    print(i,d[i])
image
3、使用items 进行遍历
d={"name":"zs","age":18}
for  k,v  in  d.items():
print(k,v)
image

(6)copy 复制
image
(7)根据键取值
image
(8)setfault  默认添加键值(不存在的)
image
默认添加键值(存在的)
image
这一点和列表不同,字典的优先级要低一些
(9)cear 清空字典
image
(10)del 删除字典,指定的键和值
image
(11)pop 删除
image
(12)popitem 随机删除末尾的键值
image
(13)fromkeys  快速生成字典
image
(14)根据get获取键对应的值
image
(15)update  更新字典
image

posted @ 2026-05-12 15:25  刘sir金牌讲师  阅读(8)  评论(0)    收藏  举报