python dict 字典
CRUD(创建,读取,更新,删除)
键值对,无序,键唯一,且是字符串,不可变,因此是可hash对象
1,创建
2,读取 (按键、值,键值进行查询)
3,更新 用的比较少
4,删除
1,创建
userinfo1={"id":1,"name":"zhangsan","ages":18,"work":"sales"}
print(type(userinfo1))
print(userinfo1)
<class ‘dict’>
{‘id’: 1, ‘name’: ‘zhangsan’, ‘ages’: 18, ‘work’: ‘sales’}
2,读取 (按键、值,键值进行查询)
#按键读取 get
userinfo1={"id":1,"name":"zhangsan","ages":18,"work":"sales"}
print(userinfo1["name"]) #直接获取
zhangsan
userinfo1={"id":1,"name":"zhangsan","ages":18,"work":"sales"}
print(userinfo1.get("name")) #通过键取到对应的值
zhangsan
userinfo1={"id":1,"name":"zhangsan","ages":18,"work":"sales"}
print(userinfo1.keys())
dict_keys([‘id’, ‘name’, ‘ages’, ‘work’])
#按值取
userinfo1={"id":1,"name":"zhangsan","ages":18,"work":"sales"}
print(userinfo1.values())
dict_values([1, ‘zhangsan’, 18, ‘sales’])
#按键值读取
userinfo1={"id":1,"name":"zhangsan","ages":18,"work":"sales"}
print(userinfo1.items())
dict_items([(‘id’, 1), (‘name’, ‘zhangsan’), (‘ages’, 18), (‘work’, ‘sales’)])
#用循环获取所有key,value
userinfo1={"id":1,"name":"zhangsan","ages":18,"work":"sales"}
for key,value in userinfo1.items():
print(key,value)
print(userinfo1)
id 1
name zhangsan
ages 18
work sales
{‘id’: 1, ‘name’: ‘zhangsan’, ‘ages’: 18, ‘work’: ‘sales’}
3,更新
userinfo1={"id":1,"name":"zhangsan","ages":18,"work":"sales"}
userinfo1["mail"]="zhangsan@qq.com" #在最后增加一个邮箱的键值对
print(userinfo1)
{‘id’: 1, ‘name’: ‘zhangsan’, ‘ages’: 18, ‘work’: ‘sales’, ‘mail’: ‘zhangsan@qq.com’}
4,删除 pop,(pop,popitem?)
userinfo1={"id":1,"name":"zhangsan","ages":18,"work":"sales"}
print(userinfo1.pop("ages")) #删除key=ages的键值对
print(userinfo1)
18
{‘id’: 1, ‘name’: ‘zhangsan’, ‘work’: ‘sales’}
#清空字典
userinfo1={"id":1,"name":"zhangsan","ages":18,"work":"sales"}
print(userinfo1.clear()) #清空字典
print(userinfo1)
None
{}