dict get with condition in Python foo = {}
print 'yes' if foo.get('bar', None) else None


Is there any way if I can improve this code?

Logic: if bar key is there, print 'yes' else print None
You can generalize what you want and create a simple function which returns yes if the key is present in your dict, otherwise returns None:

def key_exists(foo, key):
    """
    foo -&gt; dictionary
    key -&gt; lookup key
    Return foo if key exists in foo. Otherwise, return None
    """
    return 'yes' if key in foo else None

print(key_exists({'a': 'b'}, 'a'))
print(key_exists({'a': 'b'}, 'c'))
print(key_exists({}, 'c'))


The output for the above:

yes
None
None


If you, however, don't need a special message if the key is being found in the dict, and want to return a default value if it isn't found, you can do:

def key_exists(foo, key):
    """
    foo -&gt; dictionary
    key -&gt; lookup key
    Return foo if key exists in foo. Otherwise, return None
    """
    return foo.get(key, None)


The output for the above:

b
None
None


PS: Note that above (as Graipher mentioned) it's enough to directly return foo.get(key) as None is the default value anyway.

You usually want to use dict.get(key[, default]) when you need to assign default values. When get() is called, Python checks if the specified key exists in the dict. If it does, then get() returns the value of that key (which is not exactly what you want). If the key does not exist, then get() returns the value specified in the second argument to get(). That being said, you should go with the first solution

Apart from that, you should also know that doing 'key' in dict is faster than any other method. The time to find a key using this method is \$O(1)\$ whereas calling keys would generate a list and be \$O(n)\$