splitting one dictionary into two

Robert Brewer fumanchu at amor.org
Thu Apr 1 11:14:55 EST 2004


jsaul wrote:
> 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 = []
> 
>     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?

I'm not sure about "more Pythonic", but this is another way, which
iteratively destroys the original dict and produces two new ones:

def cleave(mapping, truthfunc):
    dict1, dict2 = {}, {}
    while mapping:
        key, value = mapping.popitem()
        if truthfunc(key, value):
            dict1[key] = value
        else:
            dict2[key] = value
    return dict1, dict2


HTH

Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list