Delete items in nested dictionary based on value.
Dale Strickland-Clark
dale at riverhall.nospam.co.uk
Wed Sep 13 19:50:55 EDT 2006
Brian L. Troutwine wrote:
> I've got a problem that I can't seem to get my head around and hoped
> somebody might help me out a bit:
>
> I've got a dictionary, A, that is arbitarily large and may contains
> ints, None and more dictionaries which themselves may contain ints,
> None and more dictionaries. Each of the sub-dictionaries is also
> arbitrarily large. When pretty printing A, in the context I'm using A
> for, it's rather helpful to remove all key:value pairs where value is
> None. So I'd like to be able to define a function dict_sweep to recurse
> through A and del all the keys with None as a value.
>
> I feel like the solution is right on the tip of my tounge, so to speak,
> but I just can't quite get it. Anyway, here's the best I've come up
> with:
How about this:
def dict_sweep(dictionary):
for k, v in dictionary.items():
if v is None:
del dictionary[k]
if type(v) == type({}):
dict_sweep(v)
#if len(v) == 0:
# del dictionary[k]
A_in = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None}
B_in = {1: {1: {1: None, 2: {1: None}}, 2: 2, 3: None}}
dict_sweep(A_in)
dict_sweep(B_in)
print A_in
print B_in
>>> {1: {2: 2, 3: {2: 2}}, 2: 2}
>>> {1: {2: 2}}
It doesn't produce the output you expect for B_in, but your brackets didn't
match and I'm not sure where the extra close should be. Also, I suspect
you're wanting to delete empty dictionaries but I don't see that mentioned
in the text. If that is so, include the two commented statements.
--
Dale Strickland-Clark
Riverhall Systems - www.riverhall.co.uk
More information about the Python-list
mailing list