-- coding:utf-8 --
字典常用操作
字典的特点
1. 无序
2. 键值对
3. key唯一
4. 存储一个物体相关信息(对象)
xm = {"name":"xm",
"age":12,
"gender":True,
"higet":175,
"weight":75.5}
print(xm)
1. 取值 [key]
print(xm["age"])
2. 增/改 key 不存在则新增,存在则修改
xm["pp"] = 1
xm["name"] = 2
print(xm)
3. 删除
xm.pop("pp")
print(xm)
4.统计键值对的数量
print(len(xm))
5.合并字典 如果被合并的字典保护原有的key,会覆盖掉
td = {"d":"t","age":10}
xm.update(td)
print(xm)
清空字典
xm.clear()
print(xm.keys())
print(xm.values())
print(xm.fromkeys(1))
循环
for k in xm:
print(k)
print(xm[k])
常用场景
x = {"name":"x",
"age":12}
y = {"name":"y",
"age":15}
l1 = [x,y]
for d in l1:
print(d["name"])
print(d["age"])
网友评论