Python 有条件地从 dict 中获取值?

Kev*_*ell 4 python dictionary python-3.x

给定这个 json 字符串,如何提取idif codeequals 4003 的值?

error_json = '''{
    'error': {
        'meta': {
            'code': 4003,
            'message': 'Tracking already exists.',
            'type': 'BadRequest'
        },
        'data': {
            'tracking': {
                'slug': 'fedex',
                'tracking_number': '442783308929',
                'id': '5b59ea69a9335baf0b5befcf',
                'created_at': '2018-07-26T15:36:09+00:00'
            }
        }
    }
}'''
Run Code Online (Sandbox Code Playgroud)

我不能假设除了error元素之外的任何东西都存在于开头,因此metacode元素可能存在也可能不存在。、datatrackingid可能存在也可能不存在。

id问题是如果元素都存在,如何提取值。如果缺少任何元素,则 的值id应为None

blu*_*onk 7

python 字典有一个get(key, default)方法,支持在未找到键时返回默认值。您可以链接空字典来访问嵌套元素。

# use get method to access keys without raising exceptions 
# see https://docs.quantifiedcode.com/python-anti-patterns/correctness/not_using_get_to_return_a_default_value_from_a_dictionary.html
code = error_json.get('error', {}).get('meta', {}).get('code', None)

if code == 4003:
    # change id with _id to avoid overriding builtin methods
    # see https://docs.quantifiedcode.com/python-anti-patterns/correctness/assigning_to_builtin.html
    _id = error_json.get('error', {}).get('data', {}).get('tracking', {}).get('id', None)
Run Code Online (Sandbox Code Playgroud)

现在,给定一个看起来像 JSON 的字符串,您可以使用 将其解析为字典json.loads(),如用Python 解析 JSON所示