Python 列表表达式中正确使用 dict.update
先看这样一个例子:
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)
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: