首页 > 解决方案 > 如何检查嵌套(全部)字典中是否存在多个键?

问题描述

检查是否'b' & 'c'存在于'a' & 'b'.

test = {
    'a': {
        'b': [1234],
        'c': 'some_value'
    },
    'd': {
        'b': [5678],
        'c': ''
    }
}

方法 1:如果嵌套字典数量庞大,则按以下方式工作,但实现不是很好。而且,您不能准确地通知哪个元素不存在。比方说,'c' not in 'a' , 'b' not in 'd' & 'c' not in 'd'。在这种情况下,它在第二条语句处失败(但它没有通知第三和第四条语句也失败)。我需要得到,这一切都不存在。

try:
   v1 = test['a']['b']
   v2 = test['a']['c']
   v3 = test['d']['b']
   v4 = test['d']['c']
except Exception as err:
   print(err)

方法2:

for k,v in test.items():
   if 'b' not in v:
       print("'b' doesn't exist in {}".format(test[k][v]))
   if 'c' not in v:
       print("'c' doesn't exist in {}".format(test[k][v]))

Approach1而且Approach2似乎不是很好。还有其他更好的处理方法吗?

标签: python-3.xdictionarydictionary-comprehension

解决方案


如果只有两级嵌套,您能否尝试计算低级字典中键的出现次数?例如:



counter  = {}
for el in test.keys():
    for subkey in test.get(el).keys():
        if subkey not in counter.keys():
            counter[subkey] = 1.0
        else:
            counter[subkey] += 1.0


它会回来的


{'b': 2.0, 'c': 2.0}

基于此,您可以识别嵌套键中的重复值。

然后,您可以使用set查看哪些键存在重复项:

复制密钥

counter = {k : v for k, v in counter.items() if v > 1}    

#get only values with dupe records

{k:v for k, v in test.items()  if len(set(counter.keys()).intersection(v)) > 0}


> {'a': {'b': [1234], 'c': 'some_value'}, 'd': {'b': [5678], 'c': ''}}

推荐阅读