# demo01_dict.py
info = {"name": "nfx", "age": 18, "status": True}
# 查询
# 1. 字典[键]: 通过key找到value,key不存在,代码报错
print(info["name"], info["age"], info["status"])
# print(info["height"]) # KeyError: 'height'
# 2. 字典.get(键,默认值):
# 通过key找到value; key不存在,代码不报错, 返回默认值
print(info.get("name")) # nfx
print(info.get("height")) # None
print(info.get("height","没写身高")) # 没写身高
print(info.get("age", 20)) # 18
# 3. 字典.keys(): 获取所有的key
print(info.keys())
for key in info.keys():
print(key)
# 4. 字典.values(): 获取所有的value
print(info.values())
for value in info.values():
print(value)
# 5. 字典.items(): 获取所有的kv对
print(info.items())
for item in info.items():
print(item)
# info = {"name": "nfx", "age": 18, "status": True}
# 添加和修改数据
# 1. 单值操作: 字典[键] = 值:
# 如果键不存在,则是添加操作;如果键存在,则是修改操作
info["score"] = 95 # 添加
info["age"] = 28 # 修改
# 2. 字典.update(字典)
info.update({"age": 30, "height": 180})
# 3. 字典.setdefault(key, 默认值)
# 如果字典中不存在key,由默认值为key赋值value
info.setdefault("name", "没写姓名")
info.setdefault("weight", "没写体重")
print(info)
python-----字典练习
最新推荐文章于 2024-07-03 18:56:52 发布