Take the 2-minute tour ×  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.  share|improve this question What
do you mean by "if it exists"? May the name some_var be
undefined in some cases? –  Sven Marnach Feb 14 '12 at 22:22 I
just edited it - to clarify - i'm trying to check for the
existence of a key in a dictionary essentially –  9-bits Feb 14
'12 at 22:24 I bet this has already been asked... –  Oleh Prypin
Feb 14 '12 at 22:27 See my answer for the very useful second
argument to dict.get() which nobody seems to be mentioning... – 
Endophage Feb 14 '12 at 22:28 add comment  6 Answers  up vote 3
down vote accepted  Python will throw a NameError if the
variable doesn't exist 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
function mydict.get('key', def