13.1 增加新的键值对
根据键名可直接增加。
#一个普通字典
dic_input = {"name":"lin.yi","age":23,"民族":"汉族","兴趣":["唱歌","打球"],"课程":{"统计理论":["时间序列","回归分析"],"编程语言":"python"}}
#增加一个新的键值对
dic_input["最高学历"] = "本科"
print(dic_input)
13.2 删除键值对
13.2.1. 根据键直接完全删除键值对 del
13.2.2. 弹出要删除的键对应的值,并删除该键值对pop()
#一个普通字典
dic_input = {"name":"lin.yi","age":23,"民族":"汉族","兴趣":["唱歌","打球"],"课程":{"统计理论":["时间序列","回归分析"],"编程语言":"python"}}
#1. 根据键名删除键值对
###1.1 简单,直接完全删除该键值对
del dic_input["name"]
print(dic_input)
###1.2 进阶,弹出要删除的键值对的值,并删除原键值对
print(dic_input.pop("民族"))
print(dic_input)
13.3 根据键修改对应值、根据值修改对应键
前者通过键直接指定对应新值,后者需要用pop()方法将原键值对删除,并根据新键名生成新的键值对。
#一个普通字典
dic_input = {"name":"lin.yi","age":23,"民族":"汉族","兴趣":["唱歌","打球"],"课程":{"统计理论":["时间序列","回归分析"],"编程语言":"python"}}
#1. 根据键修改对应值
dic_input["name"] = "Lin"
print(dic_input)
#2. 根据值修改对应键
dic_input["new_name"] = dic_input.pop("name")
print(dic_input)