[英]create or update python dictionary entry
Perhaps I've been spoiled by Brand X programming languages, but is there a better pythonic idiom for the following? 也许我已经被Brand X编程语言所宠爱,但是下面是否有更好的python惯用法?
thing_dict = {}
def find_or_create_thing(key):
if (thing_dict.has_key(key)):
thing = thing_dict[key]
else:
thing = create_new_thing(key)
thing_dict[key] = thing
return thing
It seems like something like this could be done in one or two lines. 这样的事情似乎可以在一两行中完成。 I considered using a Conditional Expression , but Python's odd syntax simply didn't lend itself to legibility.
我考虑过使用条件表达式 ,但是Python的奇怪语法根本无法使其易读。
I also considered a try: ... except KeyError:
, but that was just about as much text and probably considerably more execution overhead. 我还考虑过
try: ... except KeyError:
,但这try: ... except KeyError:
文本,并且可能会增加更多的执行开销。
PS I know that asking programming style questions on SO is problematic, but I'll take my chances... PS我知道在SO上询问编程风格问题是有问题的,但我会抓住机会...
Using in
is more Pythonic 使用
in
更像Pythonic
thing_dict = {}
def find_or_create_thing(key):
if not key in thing_dict:
thing_dict[key] = create_new_thing(key)
return thing_dict[key]
If you absolutely need the function on two lines: 如果您绝对需要两行功能:
thing_dict = {}
def find_or_create_thing(key):
if not key in thing_dict: thing_dict[key] = create_new_thing(key)
return thing_dict[key]
Not much shorter but maybe "prettier" (depending on the use case): 不会短很多,但可能会“更漂亮”(取决于用例):
class ThingDict(dict):
def __missing__(self, key):
self[key] = create_new_thing(key)
return self[key]
thing_dict = ThingDict()
def find_or_create_thing(key):
return thing_dict[key]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.