Test If Dictionary Key Exists, Is Not None and Isn't Blank

Test if dictionary key exists, is not None and isn't blank

Try to fetch the value and store it in a variable, then use object "truthyness" to go further on with the value

v = mydict.get("a")
if v and v.strip():
  • if "a" is not in the dict, get returns None and fails the first condition
  • if "a" is in the dict but yields None or empty string, test fails, if "a" yields a blank string, strip() returns falsy string and it fails too.

let's test this:

for k in "abcde":
v = mydict.get(k)
if v and v.strip():
print(k,"I am here and have stuff")
else:
print(k,"I am incomplete and sad")

results:

a I am here and have stuff
b I am incomplete and sad # key isn't in dict
c I am incomplete and sad # c is None
d I am incomplete and sad # d is empty string
e I am incomplete and sad # e is only blanks

if your values can contain False, 0 or other "falsy" non-strings, you'll have to test for string, in that case replace:

if v and v.strip():

by

if v is not None and (not isinstance(v,str) or v.strip()):

so condition matches if not None and either not a string (everything matches) or if a string, the string isn't blank.

Is there a way to check if a dictionary has a key, and if that key's value is not None in one pass?

Your code:

if '1' in sampleDict:
if sampleDict['1'] is not None:
#do something

Can be simplified to:

if sampleDict.get('1') is not None:
#do something

It subsumes the first if-clause by the fact that dict.get() returns None if not found. It subsumes the second if-clause by the fact that dict.get() returns the same value as [] if the key is found.

Python: Checking if a 'Dictionary' is empty doesn't seem to work

Empty dictionaries evaluate to False in Python:

>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>

Thus, your isEmpty function is unnecessary. All you need to do is:

def onMessage(self, socket, message):
if not self.users:
socket.send("Nobody is online, please use REGISTER command" \
" in order to register into the server")
else:
socket.send("ONLINE " + ' ' .join(self.users.keys()))

Return a default value if a dictionary key is not available

You can use dict.get()

value = d.get(key)

which will return None if key is not in d. You can also provide a different default value that will be returned instead of None:

value = d.get(key, "empty")

The most Pythonic way of checking if a value in a dictionary is defined/has zero length

If you know the key is in the dictionary, use

if mydict["key"]:
...

It is simple, easy to read, and says, "if the value tied to 'key' evaluates to True, do something". The important tidbit to know is that container types (dict, list, tuple, str, etc) only evaluate to True if their len is greater than 0.

It will also raise a KeyError if your premise that a key is in mydict is violated.

All this makes it Pythonic.

Check if a given key already exists in a dictionary

in tests for the existence of a key in a dict:

d = {"key1": 10, "key2": 23}

if "key1" in d:
print("this will execute")

if "nonexistent key" in d:
print("this will not")

Use dict.get() to provide a default value when the key does not exist:

d = {}

for i in range(10):
d[i] = d.get(i, 0) + 1

To provide a default value for every key, either use dict.setdefault() on each assignment:

d = {}

for i in range(10):
d[i] = d.setdefault(i, 0) + 1

or use defaultdict from the collections module:

from collections import defaultdict

d = defaultdict(int)

for i in range(10):
d[i] += 1

Check if a given key already exists in a dictionary and increment it

You are looking for collections.defaultdict (available for Python 2.5+). This

from collections import defaultdict

my_dict = defaultdict(int)
my_dict[key] += 1

will do what you want.

For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use

if key in my_dict:
my_dict[key] += 1
else:
my_dict[key] = 1

python return None if dict doesn't have key or is value is empty

You can use or operator to explicitly return None if the dict contains a empty dict

results = x.get('field') or None

But be aware that you would get None, for other types of values whole bool status is false, for example 0, '' etc.

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

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.



Related Topics



Leave a reply



Submit