how to scrutch a dict()

Ethan Furman ethan at stoneleaf.us
Fri Oct 22 20:38:48 CEST 2010


John Nagle wrote:
> On 10/22/2010 6:10 AM, Ethan Furman wrote:
>> John Nagle wrote:
> 
>>>
>>> class nonnulldict(dict) :
>>> def __setitem__(self, k, v) :
>>> if not (v is None) :
>>> dict.__setitem__(self, k, v)
>>>
>>> That creates a subclass of "dict" which ignores stores of None values.
>>> So you never store the unwanted items at all.
>>
>> It's going to take more work than that...
>>
>> --> nnd = nonnulldict(spam='eggs', ham=None, parrot=1)
>> --> nnd
>> {'ham': None, 'parrot': 1, 'spam': 'eggs'}
>> --> d['more_hame'] = None
>> --> nnd.update(d)
>> --> nnd
>> {10000:True, 'more_hame':None, 'ham':None, 'parrot':1, 'spam':'eggs'}
> 
>    You're right.
> 
> 
> class nonnulldict(dict) :
>     def __init__(self, **args) :
>         dict.__init__(self)
>         for k in args :
>             self.__setitem__(k, args[k])
>     def __setitem__(self, k, v) :
>         if not (v is None) :
>            dict.__setitem__(self, k, v)
> 
> 
> There should also be a copy constructor, so you can convert a dict to a 
> nonnulldict, a list or tuple of pairs to a nonnulldict, etc.
> But at least this will raise an exception for those cases.

The above takes care of the initialization bug, but not the update bug...

--> nnd = nonnulldict(spam='eggs', ham=None, parrot=1)
--> nnd
{'parrot': 1, 'spam': 'eggs'}
--> d = dict(more_ham = None)
--> nnd.update(d)
--> nnd
{'more_ham': None, 'parrot': 1, 'spam': 'eggs'}

I'm not sure what you mean by a copy constructor?  The copy method 
creates a new dict from the existing instance, not the other way 'round.

Basically, the dict type makes some optimizations behind the scenes, so 
doesn't always call it's own __setitem__ method.  You would have to 
override every single method that can update the dict to catch and 
discard the None valued keys.

~Ethan~



More information about the Python-list mailing list