splitting one dictionary into two

  • Thread starter Raymond Hettinger
  • Start date
R

Raymond Hettinger

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

Your way seems clean enough to me.

One other approach is to use items() so you can modify dict1 as you go:

for key, value in dict1.items():
if value > 3:
dict2[key] = value
del dict1[key]



Raymond Hettinger
 
W

wes weston

Raymond said:
[jsaul]
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?


Your way seems clean enough to me.

One other approach is to use items() so you can modify dict1 as you go:

for key, value in dict1.items():
if value > 3:
dict2[key] = value
del dict1[key]



Raymond Hettinger

Raymond,
I had the same approach seen above before the
originator added the fact that the starting
dictionaries would typically be "huge". Robert
Brewer timed this method as 5 times slower than
his method which showed me that my obsession with
simplicity needs to be looked at.
wes
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top