1

I am passing one dict to multiple functions. Say : params

def func1(self,params):
    self.data=params['KEY1']
    self.value=params['KEY2']
    self.ip=params['KEY3']
    self.template=params['KEY4']
    .....
    self.log=params['KEY10']

To avoid KeyError, i changed above code to :

def func1(self,params):
    try:
        self.data=params['KEY1']
    except KeyError:
        self.data=None
    try:
        self.value=params['KEY2']
    except KeyError:
        self.value=None
      ...
      ...

This goes for almost 10 keys, which is defiantly not right.

Is there any way i can check all the keys in once & assign None to only keys which are not present in params.

How do i check this ? Since i am also assigning the value of a key to some variable after retrieving.

Dave
  • 221
  • 2
  • 12

1 Answers1

2

You can't do it in 1 pass, but you can use the .get method:

def func1(self,params):
    self.data = params.get('KEY1')
    ...

.get returns None if no value is present at the requested key.

mgilson
  • 300,191
  • 65
  • 633
  • 696