Answer the question
In order to leave comments, you need to log in
How to shortly and quickly check in a dict for accessibility to a key?
I have this code
arr1 = {'val1': 1, 'val2': 2, 'val3': 3}
arr2 = {'val1': 6, 'val2': 7, 'val3': 8}
arr3 = {'val1': 9, 'val2': 10, 'val3': 11, 'val4': 12}
val = 'a'
if val == 'd':
try:
print(arr1['val4'])
except KeyError:
print('0000000')
elif val == 'c':
try:
print(arr2['val4'])
except KeyError:
try:
print(arr1['val4'])
except KeyError:
print('0000000')
elif val == 'a':
try:
print(arr3['val4'])
except KeyError:
try:
print(arr1['val4'])
except KeyError:
print('0000000')
Answer the question
In order to leave comments, you need to log in
arr1 = {'val1': 1, 'val2': 2, 'val3': 3}
arr2 = {'val1': 6, 'val2': 7, 'val3': 8}
arr3 = {'val1': 9, 'val2': 10, 'val3': 11, 'val4': 12}
something = {
'd': arr1,
'c': arr2,
'a': arr3,
}
default_value = '0000000'
val = 'a'
print(f"Val4: {something.get(val, {}).get('val4', default_value)}")
print(f"Val5: {something.get(val, {}).get('val5', default_value)}")
Val4: 12
Val5: 0000000
Process finished with exit code 0
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question