Use of if else inside a dict to set a value to key using Python
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'