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

  • A+
Category:Languages

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',      }    

Comment if you don't get the question. please don't downvote.

 


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',  }  ... 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: