how to convert string to number?

Tim Chase python.list at tim.thechases.com
Tue Oct 16 14:52:31 EDT 2007


> I have struggling to efficiently convert a string list to
> number. Here is my problem. I have a file that contains lines
> such as:
> 
> data_1 1 1 2 3.5
> 
> After I read the data from the file by using readlines(), each
> line contains a string. I use the re moduel to split the line
> into ['data_1', '1','1','2','3.5']. I want to create a
> dictionary which contains
> 
> {'data_1':[1 1 2 3.5]}
> 
> The problem is I coud not efficiently find a way to convert
> the string to number.
> 
> Does anyone know how to create such dictionary efficiently?

Despite my Spidey-sense tingling that this is a homework 
assignment, as similar forms of the question have popped up 
several times in the last week, I supress it this time.

Paraphrasing Andy Dufresne, "Mr. Wang, do you trust your file?"[1]

If you don't trust the content of your file, you have to know either

  1) how many columns of data to expect or
  2) the type each should be (int or float)

If the same type for each is okay, you can use something like

   >>> s = {}
   >>> for line in file('in.txt'):
   ...     k,v = line.rstrip('\n').split(None, 1)
   ...     s[k] = map(float, v.split())
   ...
   >>> s
   {'data_1': [1.0, 1.0, 2.0, 3.5], 'data_4': [1.0, 1.0, 8.0, 4.5]}

However, if you want them to be the actual types that evaluating 
them would give (thus the trust-your-source issue), you can use this:

   >>> s = {}
   >>> for line in file('in.txt'):
   ...     k,v = line.rstrip('\n').split(None, 1)
   ...     s[k] = map(eval, v.split())
   ...
   >>> s
   {'data_1': [1, 1, 2, 3.5], 'data_4': [1, 1, 8, 4.5]}


Both instances don't try to do anything smart with duplicate 
keys, so if you want to append, Bruno Desthuilliers *just* posted 
(in the last hour or so) a nice tip on this using 
setdefault().append()

-tkc

[1]http://www.finestquotes.com/movie_quotes/movie/Shawshank%20Redemption/page/0.htm








More information about the Python-list mailing list