traggatmot
traggatmot

Reputation: 1463

Multiple FOR loops in iterating over dictionary in Python

This is a simplistic example of a dictionary created by a json.load that I have t deal with:

{
    "name": "USGS REST Services Query",
    "queryInfo": {
        "timePeriod": "PT4H",
        "format": "json",
        "data": {
            "sites": [{
                "id": "03198000",
                "params": "[00060, 00065]"
            },
            {
                "id": "03195000",
                "params": "[00060, 00065]"
            }]
        }
    }
}

Sometimes there may be 15-100 sites with unknown sets of parameters at each site. My goal is to either create two lists (one storing "site" IDs and the other storing "params") or a much simplified dictionary from this original dictionary. Is there a way to do this using nested for loops with kay,value pairs using the iteritem() method?

What I have tried to far is this:

queryDict = {}

for key,value in WS_Req_dict.iteritems():
    if key == "queryInfo":
        if value == "data":
            for key, value in WS_Req_dict[key][value].iteritems():
                if key == "sites":
                    siteVal = key
                    if value == "params":
                        paramList = [value]
                        queryDict["sites"] = siteVal
                        queryDict["sites"]["params"] = paramList

I run into trouble getting the second FOR loop to work. I haven't looked into pulling out lists yet.

I think this maybe an overall stupid way of doing it, but I can't see around it yet.

Upvotes: 0

Views: 81

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 881635

I think you can make your code much simpler by just indexing, when feasible, rather than looping over iteritems.

for site in WS_Req_dict['queryInfo']['data']['sites']:
    queryDict[site['id']] = site['params']

If some of the keys might be missing, dict's get method is your friend:

for site in WS_Req_dict.get('queryInfo',{}).get('data',{}).get('sites',[]):

would let you quietly ignore missing keys. But, this is much less readable, so, if I needed it, I'd encapsulate it into a function -- and often you may not need this level of precaution! (Another good alternative is a try/except KeyError encapsulation to ignore missing keys, if they are indeed possible in your specific use case).

Upvotes: 1

Related Questions