splitting one dictionary into two
jsaul
use_reply-to at empty.invalid
Thu Apr 1 12:15:02 EST 2004
* Peter Otten [2004-04-01 18:46]:
> jsaul wrote:
>
> > 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
>
> Only a minor change to do away with the temporary list:
>
> for key in dict1:
> if dict1[key] > 3: # some criterion
> dict2[key] = dict1[key]
>
> for key in dict2:
> del dict1[key]
Hi Peter and others who responded so quickly,
I notice now that I forgot to mention an important condition,
namely that in real life dict2 is already existing and may have
become huge. That's the reason why I need to somewhere save only
those items which I most recently removed from the 1st dict, as
I want to avoid iterating over the while dict2. In real life,
dict1 contains pending jobs which, after they are done, are moved
to a second dict for post processing.
Sorry for the confusion.
I think the most "pythonic" candidate is actually the version
suggested by Larry, namely
dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 }
dict2 = {} # in real life, dict2 already exists
for key in dict1.keys():
if dict1[key] > 3:
dict2[key] = dict1.pop(key)
print dict1
print dict2
Cheers, jsaul
More information about the Python-list
mailing list