从 Dicts 获取值时的 Python If then Else 样式

发布于 2024-12-25 00:22:59 字数 469 浏览 0 评论 0原文

我经常为下面的 if/else 语法而苦苦挣扎,我希望有人能给我一些他们认为更清楚的意见,或者这是否违反了任何 Pythonism(我已经搜索过,但找不到任何东西) )。

其中之一更好还是对/错?

value = None
if 'value' in some_dict:
  value = some_dict['value']

some_func(value=value)

或:

if 'value' in some_dict:
  value = some_dict['value']
else:
  value = None

some_func(value=value)

或:

some_func(value=some_dict.get('value', None))

我可以看到所有的原因。

I often struggle with the following if/else syntax and I was hoping some people could give me some of their opinions as to what they think is more clear or if this violates any Pythonisms (I've searched and wasn't able to find anything).

Is one of these better and or right/wrong?

value = None
if 'value' in some_dict:
  value = some_dict['value']

some_func(value=value)

OR:

if 'value' in some_dict:
  value = some_dict['value']
else:
  value = None

some_func(value=value)

OR:

some_func(value=some_dict.get('value', None))

I could see reasons for all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

颜漓半夏 2025-01-01 00:23:00

当然,最后一种是最好的 - 所描述的情况正是 dict.get 的情况。

请注意 - get 的第二个参数是多余的,您可以简单地编写:

some_func(value=some_dict.get('value'))

Of course the last one is the best - described situation is exact case for dict.get.

Just a note - second parameter to get is superfluous, you can simply write:

some_func(value=some_dict.get('value'))
南街女流氓 2025-01-01 00:23:00

这对我来说看起来最自然:

value = some_dict.get('value')
some_func(value=value)

或者:最后一种情况。我回答时问题已被编辑。

This looks most natural to me:

value = some_dict.get('value')
some_func(value=value)

Or: the last case. The question was edited while I replied.

薆情海 2025-01-01 00:23:00

使用字典的 get() 方法,如第三个示例中所示。该用例正是之前的情况。

Use the dict's get() method as in your third example. That use case is exactly what it's there fore.

萌辣 2025-01-01 00:23:00

这只是一个风格问题,我会使用最后一个,因为它更简洁(注意你可以省略 None 因为它是默认值)

顺便说一句,还有这个:

value = some_dict['value'] if 'value' in some_dict else None

但这正是 .get() 确实

this is just a matter of style, I would use the last just because it's more succint (and notice you can omit the None as it is the default)

btw there's also this:

value = some_dict['value'] if 'value' in some_dict else None

but that's exactly what .get() does

苍风燃霜 2025-01-01 00:23:00

正如其他人所说, dict.get() 方法似乎是越适合您的需要。

但是,如果您不想在该值不在字典中的情况下启动该方法,则可以使用 pythonic 方式(根据 EAFP 原则)将是:

try:
   some_func(some_dict['value'])
except KeyError:
   pass

As the others said, the dict.get() method seems to be the more suitable to what you need.

BUT, if you didn't want to launch the method if the value wasn't in the dictionnary, a pythonic way (according to the EAFP principle) would have been :

try:
   some_func(some_dict['value'])
except KeyError:
   pass
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文