Python 3嵌套尝试词典中键的异常

时间:2014-09-26 14:33:28

标签: python dictionary key try-catch

有没有一种很好的方法来处理不存在的字典键?

我有一个基于字典的数据库,其中的键看起来像这样

ID
   ver
      sub_ver
           A
           B
           C

我想比较每个ID / ver / sub_ver的A,B,C键的值,以确保:

 (A==B and C==None) or (A==C and B==None) or (A==B==C)

但并非所有“ID”都有A和B以及C键/值

我的代码不是很好:

**loops outside of this for ID/ver/sub_ver** 
try:
    A = data_structure[ID][ver][sub_ver]['A']
    B = data_structure[ID][ver][sub_ver]['B']
    C = data_structure[ID][ver][sub_ver]['C']
except KeyError:
    try:
        A = data_structure[ID][ver][sub_ver]['A']
        B = data_structure[ID][ver][sub_ver]['B']
        C = None

    except KeyError: 
        try:
            A = data_structure[ID][ver][sub_ver]['A']
            B = None
            C = data_structure[ID][ver][sub_ver]['C']                    

接下来我检查所有值是否匹配

我使用set()以防A / B / C列表不按顺序

if not any((set(A)==set(B) and C==None, \
            set(A)==set(C) and B==None, \
            set(A)==set(B)==set(C))):
    set_of_problems.append([ID, ver, sub_ver, [A, B, C])

除了词典中不存在的键之外,还有更好的方法来执行嵌套try /吗?

1 个答案:

答案 0 :(得分:5)

你有太多try个;使用dict.get()获取可选元素:

try:
    A = data_structure[ID][ver][sub_ver]['A']
except KeyError:
    # no A so error, next iteration of your loop
    continue

# we know ID, ver, and sub_ver all are present
B = data_structure[ID][ver][sub_ver].get('B')
C = data_structure[ID][ver][sub_ver].get('C')

if (C is None and A == B) or (B is None and A == C) or (A == B == C):