赞
踩
{key1:value1,key2:value2}
1.key必须为不可变数据类型,必须唯一
2.可以存放多个value,可修改,可以不唯一
3.无序
4.查询速度极快,且不受dict的大小影响
person={"name":"test","age":24}
print(person)
person=dict(name="test",age=24)
print(person)
person=dict({"name":"test","age":24})
print(person)
批量赋值
keys=[1,2,3,4]
print({}.fromkeys(keys,100))
print( {}.fromkeys([1,2,3,4],100))
family={
"测试":[23,"女","tester"],
}
print("原字典:",family)
family["特斯汀"]=[24,"女","worker"]
print("增加后的字典:",family)
# key值已存在,修改value值
family["特斯汀"]=[25,"女","worker"]
print("修改后的字典:",family)
setdefault():不可修改value值
family.setdefault("学生",[18,"男","student"])
print("增加后的字典:",family)
family.setdefault("学生",[20,"男","student"])
print("测试修改后的字典:",family)
原字典
family1={
"测试":[23,"女","tester"],
"学生":[18,"男","student"],
"特斯汀":[25,"女","worker"],
"高一":[23,"女","tester"],
"高二":[23,"女","tester"],
}
print("原字典:",family1)
del family1["高一"]
print("删除后的字典:",family1)
family1.pop("高二")
print("删除后的字典:",family1)
family1.popitem()
print("删除后的字典:",family1)
family1.clear()
print("清空后的字典:",family1)
原字典
family2={
"测试":[23,"女","tester"],
"学生":[18,"男","student"],
"特斯汀":[25,"女","worker"],
"高一":[23,"女","tester"],
"高二":[23,"女","tester"],
}
print("原字典:",family2)
修改其中的一个value值
family2["特斯汀"]=[25,"女","worker"]
print("修改后的字典:",family2)
合并两个字典,key值相同取合并的值
family3={
"测试":[23,"女","test"],
"高五":[18,"男","student"],
"特斯":[22,"女","worker"],
"高四":[23,"女","tester"],
"高三":[23,"女","tester"],
}
family2.update(family3)
print("修改后的字典:",family2)
原字典
family4={
"测试":[23,"女","tester"],
"学生":[18,"男","student"],
"特斯汀":[25,"女","worker"],
"高一":[23,"女","tester"],
"高二":[23,"女","tester"],
}
print("原字典:",family4)
print("根据key查询value:",family4["测试"])#不存在,报错
print("根据key查询value:",family4.get("高洁"))#不存在返回空
print("判断key值是否存在:","ceshi" in family4)
print("查询value:",family4.values())
print("查询key:",family4.keys())
print("将key和value返回为一个元组:",family4.items())
只打印key值
for i in family4:
print(i)
打印key和value
for i in family4:
print(i,family4[i])
for i in family4.items():
print(i)
for i,j in family4.items():
print(i,j)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。