473,385 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

splitting one dictionary into two

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
Jul 18 '05 #1
7 14025
jsaul wrote:
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


jsaul,
I'll have a hack with small code. Nice that you can
iterate while removing.
wes
dict1 = { "a":1, "b":3, "c":5, "d":4, "e":2 }
dict2 = {}

print dict1

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

print dict1
print dict2

Jul 18 '05 #2
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?


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]

Peter

Jul 18 '05 #3
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" <us**********@empty.invalid> wrote in message
news:20*******************@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

Jul 18 '05 #4

"jsaul" <us**********@empty.invalid> wrote in message
news:20*******************@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?


Delete klist stuff and do deletion with

for key in dict2: del dict1[key]

tjr


Jul 18 '05 #5
* 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
Jul 18 '05 #6
jsaul wrote:
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.


jsaul,
How huge is huge?
wes

Jul 18 '05 #7
jsaul <us**********@empty.invalid> wrote in message news:<20*******************@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
Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: none | last post by:
or is it just me? I am having a problem with using a dictionary as an attribute of a class. This happens in python 1.5.2 and 2.2.2 which I am accessing through pythonwin builds 150 and 148...
2
by: Jerry | last post by:
My "main" class is getting a bit long...Is it possble to split a class definition into several files and then import the pieces to get the whole definition? Jerry
4
by: sbucking | last post by:
im trying to split a string with this form (the string is from a japanese dictionary file with mulitple definitions in english for each japanese word) str1 / (def1, ...) (1) def2 / def3 /...
2
by: David Pratt | last post by:
I have string text with language text records that looks like this: 'en' | 'the brown cow' | 'fr' | 'la vache brun' Two or more language records can exist in each string (example above shows 2...
7
by: qwweeeit | last post by:
Hi all, I am writing a script to visualize (and print) the web references hidden in the html files as: '<a href="web reference"> underlined reference</a>' Optimizing my code, I found that an...
1
by: john wright | last post by:
I have a dictionary oject I created and I want to bind a listbox to it. I am including the code for the dictionary object. Here is the error I am getting: "System.Exception: Complex...
17
by: Qiangning Hong | last post by:
I've got some strings to split. They are main words, but some words are inside a pair of brackets and should be considered as one unit. I prefer to use re.split, but haven't written a working one...
6
by: IamIan | last post by:
Hi list, I have a very simple SAX script from which I get results like 'Title1:Description','Title2:Description'. I want to split each result on the colon, using the two resulting elements as...
2
by: shadow_ | last post by:
Hi i m new at C and trying to write a parser and a string class. Basicly program will read data from file and splits it into lines then lines to words. i used strtok function for splitting data to...
1
by: sachin2 | last post by:
I am using 3 types of dictionaries. 1) Dictionary<string, string > d = new Dictionary<string, string>(); 2) Dictionary<string, List<string>> d = new Dictionary<string, List<string>>(); 3)...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.