Python有条件地从字典中获取值(value)?

标签 python python-3.x dictionary

给定这个 json 字符串,如果 code 等于 4003,我如何提取 id 的值?

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'
            }
        }
    }
}'''

我不能假设除了 error 元素之外的任何东西都存在于开头,所以 metacode 元素可能或可能不在那里。 datatrackingid 可能存在也可能不存在。

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

最佳答案

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)

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

关于Python有条件地从字典中获取值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51550279/

相关文章:

python - 如何将关键字附加到 JPG 图像中的 IPTC 数据?

python - 如何修复比较简单数据后生成的Python中的 'The truth value of a Series is ambiguous'

python - python 的文件和异常

Swift:词典词典,无法获取下标

python - 在 python 中从 CSV 文件创建字典

python - 更改键名称并添加相同键的值

python - 如何使用 xlwt 在同一个单元格中添加几个超链接?

python - 在python 2中每n毫秒在python中定期执行一个函数

python - 为什么 __all__ 应该只包含字符串对象?

python-3.x - 新型信号和插槽支持,PyQt