tags:

views:

41

answers:

1

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 ifs and continues

Thanks

+1  A: 

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
pyfunc
yup, but the number of tests that i have to perform remain the same. i was hoping i can do away with the `if` altogether
bronzebeard
@user440379 : I think the optimization may be negligible. If you used dis module to dissemble the code with or without the if check, you are removing 4 instructions only. The difference is mostly negligible.
pyfunc
oh, I agree completely, but lacks a certain finesse :)
bronzebeard
@user440379, but in the question you said "more elegant solution than having 50 different ifs and continues" and this answer is much better and i think very elegant
Anurag Uniyal
but the some other `key` might be missing in one of the nested dicts, so the number of my test remain the same. I donno, maybe this is the right way
bronzebeard
@bronzebeard : I don't think you can avoid testing for the keys since keys are already present in the dict as such. All functions that deal with the keys will inherently deal these keys in the same way, even if they are empty. So the only way to prune them would be a test on these keys.
pyfunc