title: Python: Combine "if 'x' in dict" and "for i in dict['x']"
body: <p>Really two questions:  If I have a dictionary (that originally came from parsing a json message) that has an optional array in it:</p>
  
  <pre><code>dict_with = {'name':'bob','city':'san francisco','kids': {'name': 'alice'} }
  dict_without = {'name':'bob','city':'san francisco' }
  </code></pre>
  
  <p>I would normally have code like:</p>
  
  <pre><code>if 'kids' in dict:
     for k in dict['kids']:
        #do stuff
  </code></pre>
  
  <p>My first question is there any python way to combine the if protection and the for loop?</p>
  
  <p>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:</p>
  
  <pre><code>dict_better = {'name':'bob','city':'san francisco','kids': {} }
  </code></pre>
  
  <p>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).</p>