有很多没有尝试/除了从Python字典中获取密钥或None
的方法,问题是我似乎找不到为嵌套字典执行此操作的有效方法,即我需要my_dict['author']['email']
的地方,因为两次链接.get()
会触及Nonetype。
我想扩展字典.get()
以便能够链接嵌套的字符串,即.get(['author']['email'])
- 但这意味着我必须重新启动所有自定义字典类型(我认为)?
具体情况是我有两个模式,通过它可以将数据存储在Mongodb中进行小的转换,我正在尝试找到获取正确信息的最佳方法。 (存储之前的所有数据都被验证为两个模式之一)。
例如,对于非嵌套项,可以在模式中以不同方式存储:
#get database_info
author_name = database_info['author'] if database_info.get('author') else database_info['author_name']
或
author_name = database_info['author'] if 'author' in database_info else database_info['author_name']
但对于database_info['author']['email']
(其中作者是包含其他键,值的字典对象),必须这样做:
try: author_email = database_info['author']['email']
except: database_info['contributor']['email_address']
这条线路有最佳方式吗?我考虑攻击它的一种方法是这样的(对于嵌套字典的任意路径):
author_email = database_info['author']['email'] if database_info.get('author', {}).get('email') else database_info['contributor']['email_address']
答案 0 :(得分:2)
以下是一般解决方案:
#!/usr/bin/env python
from __future__ import print_function
def select(d, *keys, **options):
try:
for key in keys:
d = d[key]
return d
except:
if "default" in options:
return options["default"]
raise
d = {
"foo": {
"bar": {
"baz": 1
}
}
}
print(select(d, "foo", "bar", "baz"))
<强>输出:强>
$ python foo.py
1
其他一些用法:
$ python -i foo.py
1
>>> select(d, "foobar")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "foo.py", line 10, in select
d = d[key]
KeyError: 'foobar'
>>> select(d, "foobar", default="Not Found")
'Not Found'
>>>
受funcy的启发,但我自己在同等功能上旋转。
答案 1 :(得分:1)
简单的案例是
author_name = database_info.get('author') or database_info['author_name']
双折案
author_email = database_info.get('author', {}).get('email') or database_info['contributor']['email_address']