python字典不存在,Python更新字典中的键(如果不存在)

本文讨论了如何在Python字典中优雅地插入键值对。通常,如果键不在字典中,可以使用`if key not in d: d[key] = value`。然而,文中建议直接使用`d[key] = value`,因为这更简洁。虽然可以使用`d[key] = d.get(key, value)`来避免KeyError,但不推荐这样做,因为它可能降低代码可读性和维护性。
摘要由CSDN通过智能技术生成

I want to insert a key-value pair into dict if key not in dict.keys().

Basically I could do it with:

if key not in d.keys():

d[key] = value

But is there a better way? Or what's the pythonic solution to this problem?

解决方案

You do not need to call d.keys(), so

if key not in d:

d[key] = value

is enough. There is no clearer, more readable method.

You could update again with dict.get(), which would return an existing value if the key is already present:

d[key] = d.get(key, value)

but I strongly recommend against this; this is code golfing, hindering maintenance and readability.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值