splitting one dictionary into two

Peter Abel PeterAbel at gmx.net
Fri Apr 2 03:58:15 EST 2004


jsaul <use_reply-to at empty.invalid> wrote in message news:<20040401153103.GC4577 at jsaul.de>...
> Hello all,
> 
> I have to split a dict into two dicts. Depending on their values,
> the items shall remain in the original dict or be moved to another
> one and at the same time be removed from the original dict.
> 
> OK, this is how I do it right now:
> 
>     dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 }
>     dict2 = {}
>     klist = []

klist is not necessary because key in dict1 will give you the
same but faster.

> 
>     for key in dict1:
>         if dict1[key] > 3: # some criterion
>             dict2[key] = dict1[key]
>             klist.append(key)
> 
>     for key in klist:
>         del dict1[key]
> 
>     print dict1
>     print dict2
> 
> That means that I store the keys of the items to be removed from
> the original dict in a list (klist) and subsequently remove the
> items using these keys.
> 
> Is there an "even more pythonic" way?
> 
> Cheers, jsaul

One solution could be:
>>> dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 }
# a little transfer-function, which deletes an item (k,v) in d and
# returns (k,v)
>>> transfer=lambda d,(k,v):[d.__delitem__(k)] and (k,v)
# transfer the items from one dict into a list and make a dict
# from it on the fly
>>> dict2=dict([transfer(dict1,(k,v)) for (k,v) in dict1.items() if v>3])
>>> dict1
{'a': 1, 'b': 3, 'e': 2}
>>> dict2
{'c': 5, 'd': 4}
>>> 

Regards
Peter



More information about the Python-list mailing list