Elegant Solution for looping over a json hash with a fickle structure
I have a json hash which has a lot of keys. I retrieve this hash from a web service at regular intervals and for different parameters etc. This has more or less fixed structure, in the sense that keys are sometimes missing. So I end up with a lot of code of the following nature
Edit:
Sample data
data =
{
id1 : {dict...},
id2 : {dict..},
'' : {value...},
...
}
for item in data:
id = data.get("id")
if not id:
continue
...
I want to skip the 3rd element and move on. The structure data
is a nested dict
and I loop inside 开发者_运维问答each of these nests. There are keys missing there as well :(
I was wondering if there was a more elegant solution than having 50 different if
s and continue
s
Thanks
How about iterating over the dict keys and doing your processing:
data = {
'id1' : {'a':"", 'b':""},
'id2' : {'c':"", 'd':""},
'' : {'c':"", 'd':""},
"": {'c':"", 'd':""},
}
for key in data.iterkeys():
if key:
print key
print "Processing %s" % key
# do further processing of data[key]
This outputs the following. Notice that it skips processing for which key is missing.
id2
Processing id2
id1
Processing id1
精彩评论