菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
3335
4

Python 列表表达式中正确使用 dict.update

原创
05/13 14:22
阅读数 3196

先看这样一个例子:

ds = [{1: '1'}, {2: '2'}, {3: '3'}]
extra = {0: '0'}
ds = [d.update(extra) for d in ds]
print(ds)
# [None, None, None]

为什么结果是 None?原因在于 d.update(extra) 是原地更新字典的,返回值为 None,但实际上 d 已经得到了更新,因此我们可以这样来写:

ds = [{1: '1'}, {2: '2'}, {3: '3'}]
extra = {0: '0'}
ds = [d.update(extra) or d for d in ds]  
# 由于 d 已经更新且 d.update(extra) 返回为 None,因此 d.update(extra) or d 返回更新后的 d
print(ds)
# [{1: '1', 0: '0'}, {2: '2', 0: '0'}, {3: '3', 0: '0'}]

持续更新日常 debug Python 过程中的小技巧和小知识,欢迎关注!

——————————————
@Joys 感谢提出 bug 及建议!这个需求源于我的一次 debug,如您所说,并非需要赋值操作,如下也是可以的:

ds = [{1: '1'}, {2: '2'}, {3: '3'}]
extra = {0: '0'}
[d.update(extra) or d for d in ds]  
print(ds)

发表评论

0/200
3335 点赞
4 评论
收藏
为你推荐 换一批