Mark
Mark

Reputation: 4706

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

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).

Upvotes: 6

Views: 4702

Answers (3)

Tauquir
Tauquir

Reputation: 6903

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

  • list comprehension are more concise to write.
  • run much faster than manual for loop statements.
  • To avoid key-error use dict_with.get('xyz',[]) returns a empty list.

Upvotes: 4

robert
robert

Reputation: 34398

for x in d.get("kids", ()):
    print "kid:", x

Upvotes: 10

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

An empty sequence results in no iteration.

for k in D.get('kids', ()):

Upvotes: 7

Related Questions