介绍
介绍
解决办法
方法1
通过in判断key是否存在my = {"nick":"福哥","age":"35","languages":["c/c++","java","php","python","javascript"]}
if "province" in my:
print(my["province"])
方法2
使用get方法判断key是否存在my = {"nick":"福哥","age":"35","languages":["c/c++","java","php","python","javascript"]}
if my.get("province") is not None:
print(my["province"])
方法3
使用get方法的第二个参数,如果目标key不存在则返回第二个参数my = {"nick":"福哥","age":"35","languages":["c/c++","java","php","python","javascript"]}
print(my.get("province", "北京"))
print(my)
方法4
使用setdefault方法的第二个参数,如果目标key不存在则返回第二个参数同时讲第二个参数写入key位置my = {"nick":"福哥","age":"35","languages":["c/c++","java","php","python","javascript"]}
print(my.setdefault("province", "北京"))
print(my)
总结