In Python what is the most efficient way to do this:
my_var = some_var['my_key'] | None
ie. assign some_var['my_key'] to my_var if some_var contains 'my_key', otherwise make my_var be None.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Python will throw a
KeyErrorif the key doesn’t exist in the dictionary so you can’t write your code in quite the same way as your JavaScript. However, if you are operating specifically with dicts as in your example, there is a very nice functionmydict.get('key', default)which attempts to get the key from the dictionary and returns the default value if the key doesn’t exist.If you just want to default to be
Noneyou don’t need to explicitly pass the second argument.Depending on what your dict contains and how often you expect to access unset keys, you may also be interested in using the
defaultdictfrom thecollectionspackage. This takes a factory and uses it to return new values from the__missing__magic method whenever you access a key that hasn’t otherwise been explicitly set. It’s particularly useful if your dict is expected to contain only one type.N.B. the docs (for 2.7.13) claim that if you don’t pass an argument to
defaultdictit’ll returnNonefor unset keys. When I tried it (on 2.7.10, it’s just what I happened to have installed), that didn’t work and I received aKeyError. YMMV. Alternatively, you can just use a lambda:defaultdict(lambda: None)