Re: Delete items in nested dictionary based on value.

2006-09-14 Thread Brian L. Troutwine
This is a general reply to all. Thanks for all the suggestions. I hadn't really thought about filtering empty dictionaries because the data I'm processing won't have them, but it does make for a much nicer, more general filter. I did end up using bearophileH's code, but that's mostly because he go

Re: Delete items in nested dictionary based on value.

2006-09-14 Thread Brian L. Troutwine
> Would it not be easier to modify the pretty-printer to ignore such > entries rather than have to make a duplicate (I presume you have reason > to need the original dictionary unchanged) dictionary and then delete > entries that match your "ignore" criteria? Good question. The data I'm hand

Re: Delete items in nested dictionary based on value.

2006-09-13 Thread bearophileHUGS
Fuzzyman: > Can you delete values from a dictionary whilst iterating over its items ? Try the code, it works. I am not iterating on the dict, I am not using dict.iteritems(), that produces a lazy iterable, I am using dict.items() that produces a list of (key,value) pairs. And I am not removing ele

Re: Delete items in nested dictionary based on value.

2006-09-13 Thread John McMonagle
> > Assuming dict_sweep worked perfectly it would take input like this: > > 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} > > and output this: > > A_out = {1: {2: 2, 3: {2: 2}}, 2: 2} > > B_out = {2:2} > > This dict_sweep ab

Re: Delete items in nested dictionary based on value.

2006-09-13 Thread Fuzzyman
[EMAIL PROTECTED] wrote: > Better: > > def clean(d): > for key,val in d.items(): > if isinstance(val, dict): > val = clean(val) > if val is None or val == {}: > del d[key] > return d Can you delete values from a dictionary whilst iterating over its

Re: Delete items in nested dictionary based on value.

2006-09-13 Thread Dale Strickland-Clark
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 dictio

Re: Delete items in nested dictionary based on value.

2006-09-13 Thread bearophileHUGS
Better: def clean(d): for key,val in d.items(): if isinstance(val, dict): val = clean(val) if val is None or val == {}: del d[key] return d a = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None} print clean(a) # Out: {1: {2: 2, 3: {2: 2}}, 2: 2} b = {1:

Re: Delete items in nested dictionary based on value.

2006-09-13 Thread bearophileHUGS
My first try, not much tested: def clean(d): for key,val in d.items(): if isinstance(val, dict): val = clean(val) if not val: del d[key] return d a = {1: {2: 2, 3: {1: None, 2: 2}}, 2: 2, 3: None} print clean(a) # Out: {1: {2: 2, 3: {2: 2}}, 2: 2} b