python字典的setdefault的巧妙用法
作者:liuzz07 时间:2021-05-18 02:58:48
现在有一个员工字典,类似这样的结构
staff_dic = {"name":"灭霸", "age": 10000, "hobbies":["打响指", "扣脚"]}
假设我们要给员工添加爱好信息,但是我们不知道hobby这个键存不存在,我们通常的做法是分为三步:
1)从字典中取到hobbies对应的值,如果没有hobbies这个键,则设置这个值为空列表
2)对这个值进行更新操作
3)将更新后的值赋值回字典
hobbies= staff_dic.get("hobby",[])
hobbies.append("毁灭宇宙")
staff_dic["hobbies"] = hobbies
以上方法进行了两次查询操作
如果使用setdefault,只需要查询一次
staff_dic.setdefault("hobbies", []).append("毁灭宇宙")
注意:setdefault()有返回值,返回值为取到的值(键存在)或默认值(键不存在)
来源:https://www.cnblogs.com/zzliu/p/10809205.html
标签:python,字典,setdefault,用法
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
ASP用户登录模块的设计源码
2008-10-03 12:16:00
Python的argparse库使用详解
2023-06-13 11:27:36
PHP入门教程之自定义函数用法详解(创建,调用,变量,参数,返回值等)
2023-10-21 05:36:58
python实现计数排序与桶排序实例代码
2023-12-28 11:32:37
![](https://img.aspxhome.com/file/2023/9/82899_0s.png)
Python 捕获代码中所有异常的方法
2022-08-31 06:44:00
Python实现多行注释的另类方法
2021-04-28 21:49:12
使用ASP遍历并列表显示目录文件
2009-11-08 18:32:00
JS中模拟函数重载
2008-01-03 16:46:00
python2 与 python3 实现共存的方法
2023-06-13 23:56:29
![](https://img.aspxhome.com/file/2023/3/59653_0s.png)
手把手教你使用Python创建微信机器人
2022-02-11 14:12:29
![](https://img.aspxhome.com/file/2023/4/64724_0s.jpg)
JS Object.preventExtensions(),Object.seal()与Object.freeze()用法实例分析
2023-09-04 22:44:33
python图像和办公文档处理总结
2021-03-08 19:24:02
![](https://img.aspxhome.com/file/2023/5/72875_0s.png)
php引用计数器进行垃圾收集机制介绍
2023-10-07 22:41:55
Python实现Word文档转换Markdown的示例
2022-06-24 08:23:29
![](https://img.aspxhome.com/file/2023/6/67296_0s.png)
Python Django 命名空间模式的实现
2023-10-06 05:34:28
![](https://img.aspxhome.com/file/2023/7/72777_0s.png)
Python3网络爬虫之使用User Agent和代理IP隐藏身份
2022-03-05 13:13:07
![](https://img.aspxhome.com/file/2023/5/79625_0s.png)
原生js实现瀑布流效果
2023-09-04 07:11:02
Python批量转换文件编码格式
2021-10-07 05:01:22
Python查找最长不包含重复字符的子字符串算法示例
2021-05-25 23:05:02
![](https://img.aspxhome.com/file/2023/8/66398_0s.png)
使用Python脚本对GiteePages进行一键部署的使用说明
2023-05-03 05:41:02
![](https://img.aspxhome.com/file/2023/2/72712_0s.jpg)