splitting one dictionary into two

Peter Otten __peter__ at web.de
Thu Apr 1 13:27:11 EST 2004


Robert Brewer wrote:

> ---- cleave.py ----
> 
EXPECTED_LEN = 100
class Unfair(Exception):
    pass

> def cleave(mapping, truthfunc):
>     """Solution by Robert Brewer."""
      if len(mapping) < EXPECTED_LEN:
          raise Unfair(str(len(mapping)))
>     dict1, dict2 = {}, {}
>     while mapping:
>         key, value = mapping.popitem()
>         if truthfunc(key, value):
>             dict2[key] = value
>         else:
>             dict1[key] = value
>     return dict1, dict2
> 
> def extractbykey(mapping, truthfunc):
>     """Solution by Peter Otten."""
      if len(mapping) < EXPECTED_LEN:
          raise Unfair(str(len(mapping)))
>     dict2 = {}
>     for key in mapping:
>         if truthfunc(key, mapping[key]):
>             dict2[key] = mapping[key]
>     
>     for key in dict2:
>         del mapping[key]
>     
>     return mapping, dict2
> 
> def inplace(mapping, truthfunc):
>     """Solution by wes weston."""
      if len(mapping) < EXPECTED_LEN:
          raise Unfair(str(len(mapping)))
>     dict2 = {}
>     for key, value in mapping.items():
>          if truthfunc(key, value): # some criterion
>              dict2[key] = value
>              del mapping[key]
> 
> --- end cleave.py ---

I suggest that you rerun your timings with the above modifications and a
dictionary of size EXPECTED_LEN.
I've got a hunch I caught you cheating :-)

Peter





More information about the Python-list mailing list