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

There are actually two questions: if I have a dictionary (which originally came from parsing a json message) that has an optional array:

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

I would usually have code like:

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

My first question is: is there a python way to combine if protection and a for loop?

Second question: my gut tells me that the best design for the original json message should always indicate the children element, just with an empty dictionary:

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

I cannot find any design methodology that confirms this. The json message is a status message from a web service that supports json and xml views. Since they started with xml, they did it so that the kids element was optional, which forces the construct above to check to see if the element exists before iterating over the array. I would like to know if it is better to constructively state that an element is required (only with an empty array if there are no elements).

+6
json python design
source share
3 answers
 for x in d.get("kids", ()): print "kid:", x 
+10
source share

An empty sequence does not iterate.

 for k in D.get('kids', ()): 
+7
source share

[x for x in dict_with.get('kids')] , you can use this filter, map - a functional programming tools with a list.

  • comprehension of the list is more concise for writing.
  • runs much faster than the manual for loop statements.
  • To avoid key-error use dict_with.get('xyz',[]) , returns an empty list.
+4
source share

All Articles