Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

python - 访问dict键,如果不存在,则返回None(Access dict key and return None if doesn't exist)

In Python what is the most efficient way to do this:

(在Python中,最有效的方法是:)

my_var = some_var['my_key'] | None

ie.

(即。)

assign some_var['my_key'] to my_var if some_var contains 'my_key' , otherwise make my_var be None .

(分配some_var['my_key']my_var如果some_var包含'my_key'否则使my_varNone 。)

  ask by 9-bits translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Python will throw a KeyError if the key doesn't exist in the dictionary so you can't write your code in quite the same way as your JavaScript.

(如果字典中不存在键,Python会抛出KeyError ,因此您无法以与JavaScript完全相同的方式编写代码。)

However, if you are operating specifically with dicts as in your example, there is a very nice function mydict.get('key', default) which attempts to get the key from the dictionary and returns the default value if the key doesn't exist.

(但是,如果您像示例中那样专门使用dict进行操作,则有一个非常不错的函数mydict.get('key', default) ,该函数尝试从字典中获取键,如果没有,则返回默认值存在。)

If you just want to default to be None you don't need to explicitly pass the second argument.

(如果您只想默认为None ,则无需显式传递第二个参数。)

Depending on what your dict contains and how often you expect to access unset keys, you may also be interested in using the defaultdict from the collections package.

(根据dict包含的内容以及期望访问未设置键的频率,您可能还对使用collections包中的defaultdict感兴趣。)

This takes a factory and uses it to return new values from the __missing__ magic method whenever you access a key that hasn't otherwise been explicitly set.

(这需要一个工厂,并在每次访问未显式设置的键时使用它从__missing__魔术方法返回新值。)

It's particularly useful if your dict is expected to contain only one type.

(如果预计您的字典仅包含一种类型,则此功能特别有用。)

from collections import defaultdict

foo = defaultdict(list)
bar = foo["unset"]
# bar is now a new empty list

NB the docs (for 2.7.13) claim that if you don't pass an argument to defaultdict it'll return None for unset keys.

(注意,文档(针对2.7.13)声称,如果不将参数传递给defaultdict它将为None设置的键返回None 。)

When I tried it (on 2.7.10, it's just what I happened to have installed), that didn't work and I received a KeyError .

(当我尝试它(在2.7.10上,它恰好是我刚安装的)时,它不起作用,我收到了KeyError 。)

YMMV.

(YMMV。)

Alternatively, you can just use a lambda: defaultdict(lambda: None)

(另外,您也可以使用lambda: defaultdict(lambda: None))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...