0

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??

1
  • Don't print what out? The name of the theater ("New York", "Ohio")? Or the key/value pair "Times": {}? Commented Jan 13, 2015 at 1:13

2 Answers 2

2

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']) 
Sign up to request clarification or add additional context in comments.

1 Comment

yes, but this errors out if there is no my_dict['Times'] the proper way would be my_dict.get('Times')
1

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)

3 Comments

lol a downvote for the answer the actually answers the question
What is the value/difference in using not any(not... versus just all?
@HuuNguyen, I would use all in this case, I just added any as another example so if the OP wanted to avoid, say just an empty dict they could use if not any(v[0]["Times"] == {} ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.