仅在尚未设置值的情况下才在dict中设置值 [英] Set a value in a dict only if the value is not already set

查看:71
本文介绍了仅在尚未设置值的情况下才在dict中设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果尚未设置>中的值,最 pythonic 方法是什么?

What is the most pythonic way to set a value in a dict if the value is not already set?

此刻,我的代码使用了if语句:

At the moment my code uses if statements:

if "timeout" not in connection_settings:
    connection_settings["timeout"] = compute_default_timeout(connection_settings)

dict.get(key,default)适用于使用dict的代码,不适用于准备将dict传递给另一个函数的代码.您可以使用它来设置某些内容,但它不是更漂亮的imo:

dict.get(key,default) is appropriate for code consuming a dict, not for code that is preparing a dict to be passed to another function. You can use it to set something but its no prettier imo:

connection_settings["timeout"] = connection_settings.get("timeout", \
    compute_default_timeout(connection_settings))

即使字典包含键,也将评估计算功能;错误.

would evaluate the compute function even if the dict contained the key; bug.

Defaultdict是默认值相同的时间.

Defaultdict is when default values are the same.

当然,您有很多次设置不需要计算的原始值作为默认值,它们当然可以使用dict.setdefault.但是更复杂的情况呢?

Of course there are many times you set primative values that don't need computing as defaults, and they can of course use dict.setdefault. But how about the more complex cases?

推荐答案

这是一个无法回答的问题,但是我要说的是,最Python化的是if语句.您抵制了用__setitem__或其他方法将其单线书写的冲动.您已经避免了由于现有的但虚假的值而可能导致的逻辑错误,当试图巧妙地使and/or短路时,可能会发生错误.显而易见,在不需要时不使用计算功能.

This is a bit of a non-answer, but I would say the most pythonic is the if statement as you have it. You resisted the urge to one-liner it with __setitem__ or other methods. You've avoided possible bugs in the logic due to existing-but-falsey values which might happen when trying to be clever with short-circuiting and/or hacks. It's immediately obvious that the compute function isn't used when it wasn't necessary.

清晰,简洁,可读- pythonic .

It's clear, concise, and readable - pythonic.

这篇关于仅在尚未设置值的情况下才在dict中设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆