Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Combine "if 'x' in dict" and "for i in dict['x']"

Tags:

python

json

Really two questions: If I have a dictionary (that originally came from parsing a json message) that has an optional array in it:

dict_with = {'name':'bob','city':'san francisco','kids': {'name': 'alice'} }
dict_without = {'name':'bob','city':'san francisco' }

I would normally have code like:

if 'kids' in dict:
   for k in dict['kids']:
      #do stuff

My first question is there any python way to combine the if protection and the for loop?

The second question is my gut tells me the better design for the original json message would be to always specify the kids element, just with an empty dictionary:

dict_better = {'name':'bob','city':'san francisco','kids': {} }

I can't find any design methodology that substantiates this. The json message is a state message from a web service that supports json and xml representations. Since they started with xml, they made it so the "kids" element was optional, which forces the construct above of checking to see if the element exists before iterating over the array. I would like to know if it's better design-wise to say the element is required (just with an empty array if there are no elements).

like image 530
Mark Avatar asked Dec 16 '10 18:12

Mark


1 Answers

for x in d.get("kids", ()):
    print "kid:", x
like image 174
robert Avatar answered Oct 20 '22 19:10

robert