如何有效地检查嵌套dict和数组中是否存在密钥

2024-05-04 19:02:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在想,当涉及到从dict获取值时,如何KISS

存在各种场景,例如:

  1. 密钥不存在(应返回默认值{}/[]/“”)
  2. 该键包含一个空列表值(然后应返回空列表)
  3. 如果我们试图获取一个值,例如test['objects'][0]['productInfo'][0]['merchPrice']['promoExclusions'][0],并且它在productInfo已经失败,那么它应该立即返回默认值,而不是继续搜索下一个键

我最终做了这样的事情:

test = {
  'pages': {
    'prev': '',
  },
  'objects': [
    {
      'id': 'c362b8f3-1862-4e2d-ba06-d910e0d98e7e',
      'productInfo': [
        {
          'merchProduct': {
            'id': '63912b18-f00f-543f-a5c5-0c6236f63e79',
            'snapshotId': '43cf801e-3689-42c2-ac85-d404e69aba42',

          },
          'merchPrice': {
            'id': '7dd81061-d933-57f6-b233-2a6418ce487d',
            'snapshotId': '268cc5af-8e04-4d64-b19b-02c2770b91fb',
            'discounted': False,
            #Could be | 'promoExclusions': ['TRUE'],
            'promoExclusions': [],
            'resourceType': 'merchPrice',
          }
        }
      ]
    }
  ]
}


if test_print := test['objects'][0]['productInfo'][0]['merchPrice']['promoExclusions'][0]:
   print(test_print)

但是,这会返回一个错误IndexError: list index out of range,因为该列表不包含任何有意义的值,但我想知道在这种情况下如何为该粒子问题设置默认值

我的问题是: 我如何使它尽可能简单高效地查找和获取dict的值,而不需要使用大量资源,如果找不到,则返回默认值


Tags: testid列表objects场景密钥pageskiss
3条回答

How can I keep it as simple as possible and efficiently to find and get the value of a dict without needing to use alot of resources and if its not found then return a default value?

这个问题的答案是使用^{}

>>> import collections
>>> d = collections.defaultdict(list, {'key1': [1], 'key2': [2]})
>>> d['key1']
[1]
>>> d['key3']
[]

对于单个dict,您可以使用d.get('key', default),但是对于嵌套提取字符串没有简单的快捷方式。你可以用try/except来做

try:
    test_print = test['objects'][0]['productInfo'][0]['merchPrice']['promoExclusions'][0]
except KeyError:
    test_print = default_value
print(test_print)

你试过使用try except吗? 下面的代码段打印您试图访问的词典的值,或者在发生异常时打印默认值

default = 'default {}/[]/""'
try:
    print(test['objects'][0]['productInfo'][0]['merchPrice']['promoExclusions'][0])
except (KeyError, IndexError):
    print(default)

相关问题 更多 >