-1

I have a list of dictionary accepting the user Input values as shown below:

def get_params(app_name):
    return [
           {'Key':'Path', 'Value': event['Path']},
           {'Key':'TargetType', 'Value': event['Target']},
           {'Key': 'Owner', 'Value': event['Owner']}
          ]

def lambda_handler(event,context):
     params = get_params('hello')
     print(params)

How to set default values for Path as / and TargetType as Truefor example, so that if user has not passed any value, it picks the default value?

Edit: Wanted to have default value set for Path, in case the value of event['Path'] is not found or is null.

rsram312
  • 99
  • 2
  • 13
  • 3
    What is a "lambda event"? All I see is a function? Are you using some framework? – cs95 Jan 19 '19 at 21:10
  • Sorry for using the term lambda event. Edited the question. Basically wanted to set default values in `get_params` function for all the keys. – rsram312 Jan 19 '19 at 21:18
  • From the parameters, I assume this is an AWS lambda function, which has nothing to do with a python lambda; I've updated the tag. – Daniel Roseman Jan 19 '19 at 21:19
  • @DanielRoseman Thanks for that. Ya I was intending to add aws-lambda as a tag. – rsram312 Jan 19 '19 at 21:28
  • This actually has nothing to do with AWS Lambda, aside from the fact that AWS Lambda calls the `lambda_handler()` event. After that, it is all standard Python. – John Rotenstein Jan 19 '19 at 22:03
  • Yeah ! Hence added that as edit , basically wanted to know how to set default values in list of dictionary . If it was just a dictionary, could have used ‘get’ and set default value . Now was wondering how to do in case of list of dictionary. – rsram312 Jan 19 '19 at 22:05
  • Possible duplicate of [Python: default dict keys to avoid KeyError](https://stackoverflow.com/questions/24814024/python-default-dict-keys-to-avoid-keyerror) – Uri Goren Jan 19 '19 at 22:14

2 Answers2

2

A python dict has two ways of addressing its values:

  1. events["path"] - would raise an exception if "path" not in events
  2. events.get("path", "default") - would return "default" if the key is missing
Uri Goren
  • 13,386
  • 6
  • 58
  • 110
  • Thanks Uri ! This was what i was looking for. Probably, the way I put the question forward was confusing. – rsram312 Jan 19 '19 at 22:19
1

It appears that your requirements are:

  • get_params() should return values from event[]
  • Substitute default values if the values are not provided

You could use:

def get_params(app_name):
    return [
           {'Key':'Path', 'Value': event.get('Path', '/')},
           {'Key':'TargetType', 'Value': event.get('Target', True)},
           {'Key': 'Owner', 'Value': event['Owner']}
          ]
John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
  • Thanks a lot John !! This is what I was looking for. I was trying to use `get` , but had got the syntax wrong inside a list of dictionary. Thanks again, this worked perfectly :+1: – rsram312 Jan 19 '19 at 22:17