Python知识学习07——字典

字典类型:dict

Python字典的增删改查

增:

1
2
3
stu = {"name":"Rose"}
stu["age"] = 22
print(stu)

删:

1
2
3
stu = {"name":"Rose", "age":22}
del stu["name"]
print(stu)

提示:如果删除的是不存在的key,则会报错

改:

1
2
3
stu = {"name":"Rose", "age":22}
stu["age"] = 30
print(stu)

查:

1
2
3
stu = {"name":"Rose", "age":22}
age = stu["age"]
print(age)

提示:使用这种查询方法,如果键不存在,则会报错

1
2
3
4
>>> stu = {"name":"Rose", "age":22}
>>> age = stu.get("age")
>>> print(age)
22
1
2
3
4
>>> stu = {"name":"Rose", "age":22}
>>> address = stu.get("address")
>>> print(address)
None

提示:使用这种查询方法,如果键不存在,不会报错

查询字典当中是否存在某个键:

1
2
3
>>> stu = {"name":"Jack", "age":"22"}
>>> "name" in stu
True
1
2
3
>>> stu = {"name":"Jack", "age":"22"}
>>> "name" in stu.keys()
True

查询字典当中是否存在某个值:

1
2
3
>>> stu = {"name":"Jack", "age":"22"}
>>> "Jack" in stu.values()
True