splitting one dictionary into two

Larry Bates lbates at swamisoft.com
Thu Apr 1 11:56:07 EST 2004


There a quite a few different ways to do this, but
I might suggest something like:

    dict1={"a":1, "b":3, "c":5, "d":4, "e":2}
    dict2={}
    dict3={}
    [dict2.setdefault(k,v) for k,v in dict1.items() if v > 3]
    [dict3.setdefault(k,v) for k,v in dict1.items() if not v > 3]
    dict1=dict3.copy()

Very "Pythonic" but is 2 times slower than your original code.

Another suggestion is:

    dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 }
    dict2 = {}

    keys=dict1.keys()
    for key in keys:
        if dict1[key] > 3: # some criterion
            dict2[key] = dict1[key]
            del dict1[key]

This is a "little" faster (100000 iterations of your method
time=1.13 seconds, my method=0.94 seconds and I find easier
to read (eliminates the unneeded klist variable and second
loop).

Larry Bates
Syscon, Inc.

"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 = []
>
>     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





More information about the Python-list mailing list