How to Check Dictionary Value Is Empty or Not

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.

Pythonic way to check empty dictionary and empty values

Test with any, since empty dicts are falsy:

>>> collection_a = {}
>>> collection_b = {"test": {}}
>>> any(collection_a.values())
False
>>> any(collection_b.values())
False

This assumes that the dictionary value is always a dictionary.

How to check if a dictionary is empty?

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()))

Check if dictionary is empty but with keys

Your dictionary is not empty, only your values are.

Test each value, using the any function:

if not any(data.values()):
# all values are empty, or there are no keys

This is the most efficient method; any() returns True as soon as it encounters one value that is not empty:

>>> data = {'news': [], 'ad': [], 'coupon': []}
>>> not any(data.values())
True
>>> data["news"].append("No longer empty")
>>> not any(data.values())
False

Here, not empty means: the value has boolean truth value that is True. It'll also work if your values are other containers (sets, dictionaries, tuples), but also with any other Python object that follows the normal truth value conventions.

There is no need to do anything different if the dictionary is empty (has no keys):

>>> not any({})
True

check if the value in a dict is not empty?

You need to iterate over the dict["Showtimes"] items then access the dict in the list using the Times key and check using an if which will return False for an empty dict.

d = {"Showtimes":{
"New York": [
{
"Times": {},
"theaterid": 61,
}
],
"Ohio": [
{
"Times": {'2015-01-10',
'2015-01-11'},
"theaterid": 1,
}
]
}}

for k,v in d["Showtimes"].iteritems():
if v[0]["Times"]:
print(k,v)
('Ohio', [{'theaterid': 1, 'Times': set(['2015-01-10', '2015-01-11'])}])

One thing to be careful of is if you have a value like 0, this will also return False so if you only want to check if the value is an empty dict use if v[0]["Times"] != {}

If you want to check all values of Times and only print the full dict if there are no empty Times values you can use all which will short circuit on the first occurrence of an empty value:

if all(v[0]["Times"] for v in d["Showtimes"].itervalues()):
print(d)

Or reverse the logic with any:

if not any(not v[0]["Times"] for v in d["Showtimes"].itervalues()):
print(d)

If there is a chance a dict won't have a Times key use v[0].get("Times",1)

How to check dictionary value is empty or not

Check length if you wanna check your string value. for example

func doValidate(data:Dictionary<String,AnyObject>,isEmail : String) -> Bool {
if(isEmail=="signup"){
if( data["last_name"]?.length == 0 || data["email"]?.length == 0 || data["password"]?.length == 0 || data["first_name"]?.length == 0){
return false;
}
else{
return true;
}
}
}

How to check if dictionary is empty and dictionary is like {:} in python

Use dict.keys() to get all the keys. You can then compare this to a tuple with just "" in it.

if tuple(d.keys()) == ("",):
print("dict is empty")

One liner to determine if dictionary values are all empty lists or not

Per my testing, the following one-liner (my original answer) has best time performance in all scenarios. See edits below for testing information. I do acknowledge that solutions using generator expressions will be much more memory efficient and should be preferred for large dicts.

EDIT: This is an aging answer and the results of my testing may not be valid for the latest version of python. Since generator expressions are the more "pythonic" way, I'd imagine their performance is improving. Please do your own testing if you're running this in a 'hot' codepath.

bool([a for a in my_dict.values() if a != []])

Edit:

Decided to have some fun. A comparison of answers, not in any particular order:

(As used below, timeit will calculate a loop order of magnitude based on what will take less than 0.2 seconds to run)

bool([a for a in my_dict.values() if a != []]) :

python -mtimeit -s"my_dict={'a':[],'b':[]}" "bool([a for a in my_dict.values() if a != []])"
1000000 loops, best of 3: 0.875 usec per loop

any([my_dict[i] != [] for i in my_dict]) :

python -mtimeit -s"my_dict={'a':[],'b':[]}" "any([my_dict[i] != [] for i in my_dict])"
1000000 loops, best of 3: 0.821 usec per loop

any(x != [] for x in my_dict.itervalues()):

python -mtimeit -s"my_dict={'a':[],'b':[]}" "any(x != [] for x in my_dict.itervalues())"
1000000 loops, best of 3: 1.03 usec per loop

all(map(lambda x: x == [], my_dict.values())):

python -mtimeit -s"my_dict={'a':[],'b':[]}" "all(map(lambda x: x == [], my_dict.values()))"
1000000 loops, best of 3: 1.47 usec per loop

filter(lambda x: x != [], my_dict.values()):

python -mtimeit -s"my_dict={'a':[],'b':[]}" "filter(lambda x: x != [], my_dict.values())"
1000000 loops, best of 3: 1.19 usec per loop




Edit again - more fun:

any() is best case O(1) (if bool(list[0]) returns True). any()'s worst case is the "positive" scenario - a long list of values for which bool(list[i]) returns False.



Check out what happens when the dict gets big:

bool([a for a in my_dict.values() if a != []]) :

#n=1000
python -mtimeit -s"my_dict=dict(zip(range(1000),[[]]*1000))" "bool([a for a in my_dict.values() if a != []])"
10000 loops, best of 3: 126 usec per loop

#n=100000
python -mtimeit -s"my_dict=dict(zip(range(100000),[[]]*100000))" "bool([a for a in my_dict.values() if a != []])"
100 loops, best of 3: 14.2 msec per loop

any([my_dict[i] != [] for i in my_dict]):

#n=1000
python -mtimeit -s"my_dict=dict(zip(range(1000),[[]]*1000))" "any([my_dict[i] != [] for i in my_dict])"
10000 loops, best of 3: 198 usec per loop

#n=100000
python -mtimeit -s"my_dict=dict(zip(range(100000),[[]]*100000))" "any([my_dict[i] != [] for i in my_dict])"
10 loops, best of 3: 21.1 msec per loop



But that's not enough - what about a worst-case 'False' scenario?

bool([a for a in my_dict.values() if a != []]) :

python -mtimeit -s"my_dict=dict(zip(range(1000),[0]*1000))" "bool([a for a in my_dict.values() if a != []])"
10000 loops, best of 3: 198 usec per loop

any([my_dict[i] != [] for i in my_dict]) :

python -mtimeit -s"my_dict=dict(zip(range(1000),[0]*1000))" "any([my_dict[i] != [] for i in my_dict])"
1000 loops, best of 3: 265 usec per loop

Check if list values in dictionary are not empty

Try using Linq:

 Dictionary<DateTime,List<string>> dictionary = ...

bool hasNotEmptyValues = dictionary
.Any(pair => pair.Value != null && pair.Value.Any());

check if dictionary key has empty value

This would have to be the fastest way to do it (using set difference):

>>> dict1 = {"city":"","name":"yass","region":"","zipcode":"",
"phone":"","address":"","tehsil":"", "planet":"mars"}
>>> blacklist = {"planet","tehsil"}
>>> {k: dict1[k] for k in dict1.viewkeys() - blacklist if dict1[k]}
{'name': 'yass'}

White list version (using set intersection):

>>> whitelist = {'city', 'name', 'region', 'zipcode', 'phone', 'address'}
>>> {k: dict1[k] for k in dict1.viewkeys() & whitelist if dict1[k]}
{'name': 'yass'}


Related Topics



Leave a reply



Submit