F
F
fantom_ask2020-07-24 15:45:49
Python
fantom_ask, 2020-07-24 15:45:49

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')

And I'm wondering if it's possible to optimize it somehow?
Because when adding new arr4,arr5,arr6,arr7 arr... . the whole code will turn into an endless list of conditions

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
ScriptKiddo, 2020-07-24
@fantom_ask

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)}")

OUT
Val4: 12
Val5: 0000000

Process finished with exit code 0

D
Dr. Bacon, 2020-07-24
@bacon

Go read the docs, really only cry from such code
1. for not hearing about dict.get(key), kicking
2. for not hearing about KeyError, kicking twice.
3. common except - beat until blue in the face

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question