Use of if else inside a dict to set a value to key using Python

Viewed 14024

I am looking for a way to use if else condition in a dictionary to set a value to a key. Is there a way?

The example below might help you understand what I want to do. This is not a functional Python code. Just an example to give you an idea.

age = 22
di = {
    'name': 'xyz',
    if age>=18:
        'access_grant': 'yes',
    else:
        'access_grant': 'no',
     }   
3 Answers

I think this would be a perfect opportunity to use a ternary expression (python also calls this the "ternary operator"):

...
di = {
    'name': 'xyz',
    'access_grant': 'yes' if age >= 18 else 'no',
 } 
...

You can separate the logic from the dictionary with a function:

def access_grant(age):
    if age >= 18:
        return 'yes'
    return 'no'

age = 22
di = {
    'name': 'xyz',
    'access_grant': access_grant(age),
}

Having the logic outside of the dictionary makes it easier to test and reuse.

Set as many items as you can in the initial definition, then add the others afterwards:

age = 22
di = {
    'name': 'xyz',
    ... other known keys here
}
if age>=18:
    di['access_grant'] = 'yes'
else:
    di['access_grant'] = 'no'
Related