我有一本嵌套的字典。是否只有一种方法可以安全地传递价值观?
try:
example_dict['key1']['key2']
except KeyError:
pass
或者python有一个类似get()的方法用于嵌套字典?
我有一本嵌套的字典。是否只有一种方法可以安全地传递价值观?
try:
example_dict['key1']['key2']
except KeyError:
pass
或者python有一个类似get()的方法用于嵌套字典?
当前回答
我建议你试试蟒蛇本尼迪克特。
它是一个dict子类,提供小键盘支持等功能。
安装:pip install python-benedict
from benedict import benedict
example_dict = benedict(example_dict, keypath_separator='.')
现在你可以使用keypath访问嵌套值:
val = example_dict['key1.key2']
# using 'get' method to avoid a possible KeyError:
val = example_dict.get('key1.key2')
或者使用键列表访问嵌套值:
val = example_dict['key1', 'key2']
# using get to avoid a possible KeyError:
val = example_dict.get(['key1', 'key2'])
它在GitHub上经过了很好的测试和开源:
https://github.com/fabiocaccamo/python-benedict
注:我是这个项目的作者
其他回答
如果您想使用另一个库来解决问题,这是最好的方法
https://github.com/maztohir/dict-path
from dict-path import DictPath
data_dict = {
"foo1": "bar1",
"foo2": "bar2",
"foo3": {
"foo4": "bar4",
"foo5": {
"foo6": "bar6",
"foo7": "bar7",
},
}
}
data_dict_path = DictPath(data_dict)
data_dict_path.get('key1/key2/key3')
你可以使用开源ndicts包中的NestedDict(我是作者),它有一个完全像字典一样的安全get方法。
>>> from ndicts import NestedDict
>>> nd = NestedDict({"key1": {"key2": 0}}
>>> nd.get(("key1", "key2))
0
>>> nd.get("asd")
因为如果缺少一个键就会引发一个键错误是合理的,我们甚至可以不检查它,让它像这样单一:
def get_dict(d, kl):
cur = d[kl[0]]
return get_dict(cur, kl[1:]) if len(kl) > 1 else cur
我改编了GenesRus和unutbu的答案,非常简单:
class new_dict(dict):
def deep_get(self, *args, default=None):
_empty_dict = {}
out = self
for key in args:
out = out.get(key, _empty_dict)
return out if out else default
它适用于:
d = new_dict(some_data)
d.deep_get("key1", "key2", "key3", ..., default=some_value)
根据Yoav的回答,一个更安全的方法是:
def deep_get(dictionary, *keys):
return reduce(lambda d, key: d.get(key, None) if isinstance(d, dict) else None, keys, dictionary)