Skip to content Skip to sidebar Skip to footer

Iterate Over Nested Dictionaries

below is a dictionary that i have create for a project. I am trying to iterate over the list values but keep getting errors moo = {'dell': {'strengths': {'dell strengths': ['http:/

Solution 1:

It sounds like googlelinks() is returning a list, not a dictionary. You just iterate over that using for v in moo[k][sk][mk]:. No need for items() unless you're using a dictionary in particular.

EDIT: it's unclear why you're using keys() for most of the code and them items() later. The items() function will return both the key and the value for a given dictionary item, which lets you simplify your code greatly. You can eliminate nested calls like moo[k][sk][mk] by doing something like this instead (thanks Martijn):

for k, v in moo.items():  # v = moo[k]
#base.add_sheet(k)
    for sk, sv in v.items():  # sv = v[sk] = moo[k][sk]
    #print sk
        for mk, mv in sv.items():  # mv = sv[mk] = v[sk][mk] = moo[k][sk][mk]
            sv[mk] = googlelinks(mk,2)
            for gv in sv[mk]:
                print gv

On another note, you may want to give your variables less cryptic names, so your code is easier to follow. Ideally, we should know from reading your variable names what's stored in each dictionary.


Post a Comment for "Iterate Over Nested Dictionaries"