I have a dict theaterinfo like this :
"Showtimes":{ "New York": [ { "Times": {}, "theaterid": 61, } ] "Ohio": [ { "Times": {'2015-01-10', '2015-01-11'}, "theaterid": 1, } ] } How can I deal with that if Times in empty,don't print it out??
An empty dictionary evaluates to a boolean False while a non-empty dict evaluates to True, so you can write
if my_dict['Times']: print(my_dict['Times']) my_dict['Times'] the proper way would be my_dict.get('Times')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)
not any(not... versus just all?if not any(v[0]["Times"] == {} ...
"New York","Ohio")? Or the key/value pair"Times": {}?