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).
for x in d.get("kids", ()):
print "kid:", x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With