字典中键的Python 3嵌套try异常
有没有处理不存在的字典键的好方法 我有一个基于字典的数据库,它的键看起来像这样字典中键的Python 3嵌套try异常,python,dictionary,key,try-catch,Python,Dictionary,Key,Try Catch,有没有处理不存在的字典键的好方法 我有一个基于字典的数据库,它的键看起来像这样 ID ver sub_ver A B C 我想比较每个ID/ver/sub版本的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 fo
ID
ver
sub_ver
A
B
C
我想比较每个ID/ver/sub版本的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/except 你有太多的
尝试;使用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):
你有太多的尝试;使用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):
这可能是你感兴趣的。这可能是你感兴趣的。啊,让它工作吧!此外,为了处理列表中的值,我在get函数中添加了默认值。get('B',[None]),并将C is None更改为C==[None]@user2987193:您需要使用set()
这里有一个单独的问题;它不会对原始问题和该问题的解决方案产生影响。啊,get()有效!此外,为了处理列表中的值,我在get函数中添加了默认值。get('B',[None]),并将C is None更改为C==[None]@user2987193:您需要使用set()
这里有一个单独的问题;它不会对原始问题和该问题的解决方案产生影响。