访问dict键,如果不存在,则返回None [英] Access dict key and return None if doesn't exist

查看:268
本文介绍了访问dict键,如果不存在,则返回None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

my_var = some_var['my_key'] | None

即.如果some_var包含'my_key',则将some_var['my_key']分配给my_var,否则将my_var设置为None.

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

推荐答案

如果密钥在字典中不存在,Python将抛出KeyError,因此您无法以与JavaScript完全相同的方式编写代码.但是,如果像示例中那样专门使用dict进行操作,则有一个非常不错的函数mydict.get('key', default)尝试从字典中获取键,如果键不存在,则返回默认值.

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. 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.

如果只想将默认值设置为None,则无需显式传递第二个参数.

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

根据您的词典包含的内容以及您期望访问未设置键的频率,您可能还对使用

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. 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. 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

文档(针对2.7.13)声称,如果不将参数传递给defaultdict,它将为未设置的键返回None.当我尝试使用它(在2.7.10上,这恰好是我刚安装的)时,它不起作用,我收到了KeyError. YMMV.另外,您也可以使用lambda:defaultdict(lambda: None)

N.B. the docs (for 2.7.13) claim that if you don't pass an argument to defaultdict it'll return None for unset keys. 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. YMMV. Alternatively, you can just use a lambda: defaultdict(lambda: None)

这篇关于访问dict键,如果不存在,则返回None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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