mvarge
mvarge

Reputation: 324

Convert only one item with dictionary comprehension

Cheers,

I'm currently working on a piece of code and and I'm trying to find the best, more pythonic and CPU low cost solution for my problem.

I actually have a array of "index value" which I read through a file, an example is:

>>> list = ['index_1    200', 'index_2    500', 'index_3    50']
>>>
>>> list
['index_1    200', 'index_2    500', 'index_3    50']

I'm trying to create a dictionary comprehension where I will maintain the index name as a string but convert the value to an int. The way I've found to accomplish this goal was:

>>> dict((line.split()[0], int(line.split()[1])) for line in list)
{'index_2': 500, 'index_3': 50, 'index_1': 200}

But the (line.split()[0], int(line.split()[1]) part looks like something that could be done in a better way, since that my list example is really just an example, I may find huge lines of indexes later on.

Thanks for any help.

Upvotes: 1

Views: 89

Answers (1)

khelwood
khelwood

Reputation: 59096

You can avoid splitting each string twice, and you can make use of a dictionary comprehension like this:

>>> mylist = ['index_1    200', 'index_2    500', 'index_3    50']
>>> mydict = {k:int(v) for (k,v) in (line.split() for line in mylist)}
>>> mydict
{'index_2': 500, 'index_3': 50, 'index_1': 200}

Edit

In Python 2.6 you can do pretty much the same thing but without the dict comprehension syntax:

 >>> mydict = dict((k,int(v)) for (k,v) in (line.split() for line in mylist))

Upvotes: 8

Related Questions