Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a key exists and its value is not an empty string in a Python dictionary

Is there a clear best practice for assigning a variable from a key/value pair in a Python dictionary:

  • If the key is present
  • If the key's value is not an empty string

And otherwise assigning a default value to the variable.

I would like to use dict.get:

my_value = dict.get(key, my_default) 

But this assigns an empty string to my_value if the key is present and the value is an empty string. Is it better to use the following:

if key in dict and dict[key]:     my_value = dict[key] else:     my_value = my_default 

This would make use of the truthfulness of an empty string to ensure only non-empty strings were assigned to my_value.

Is there a better way to perform this check?

like image 653
Jonathan Evans Avatar asked Jan 14 '13 17:01

Jonathan Evans


People also ask

How do you check if a key exists in a dictionary in Python?

Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.

How do you check if a key-value pair exists in a dictionary Python?

Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.

How do I check if a key is empty in Python?

Check if a Python Dictionary is Empty by Checking Its Lengthif len(empty_dict) == 0: print('This dictionary is empty! ')


1 Answers

Maybe you mean something like:

a.get('foo',my_default) or my_default 

which I think should be equivalent to the if-else conditional you have

e.g.

>>> a = {'foo':''} >>> a.get('foo','bar') or 'bar' 'bar' >>> a['foo'] = 'baz' >>> a.get('foo','bar') or 'bar' 'baz' >>> a.get('qux','bar') or 'bar' 'bar' 

The advantages to this over the other version are pretty clear. This is nice because you only need to perform the lookup once and because or short circuits (As soon as it hits a True like value, it returns it. If no True-like value is found, or returns the second one).

If your default is a function, it could be called twice if you write it as: d.get('foo',func()) or func(). In this case, you're better off with a temporary variable to hold the return value of func.

like image 194
mgilson Avatar answered Sep 22 '22 21:09

mgilson