python - TypeError deleting items in a nested dictionary -
i have nested dictionary following:
g = { 'a': { 1.55: { 'cd': [1.55, 12], 'lm': [1.55, 12], }, 1.45: { 'af': [1.45, 15], }, 1.6: { 'nr': [1.6, 26], } } }
i want search through every element, , remove if has 12 in list. i've written following code, typeerror
. wondering if help.
for e, p in g.iteritems(): p,o in g[e].iteritems(): if g[e][p][o][1]==12: del g[e][p][o]
because o
dictionary, can't use index, why receiving typeerror
.
the following code want, urge think of better way can organize data.
for k1 in g.keys(): k2 in g[k1].keys(): k3 in g[k1][k2].keys(): if 12 in g[k1][k2][k3]: del g[k1][k2][k3]
note need use .keys()
instead of .iterkeys()
avoid runtimeerror: dictionary changed size during iteration
. similarly, in @eric's solution .items()
should used instead of .iteritems()
Comments
Post a Comment