putting int/float from file into a dictionary
<p>I like to put some values from a csv file into a dict. An example is:</p>

<pre><code>TYPE, Weldline

Diam, 5.0

Num of Elems, 4
</code></pre>

<p>and I end up after reading into a dictionary (for later use in an API) in:</p>

<pre><code> {'TYPE':'Weldline' , 'Diam':'5.0','Num of Elems':'4'}
</code></pre>

<p>Since the API expects a dictionary i provided all the necessary keywords like 'TYPE', 'Diam', ... according to the API doc.</p>

<p>The problem I have is, that the API expects a float for <code>Diam</code> and an integer for <code>Num of Elems</code></p>

<p>Since I have a large number of entries: is there an simple automatic way for string conversion into float or int?
Or do I have to write something on my own?</p>

<p>You can use <code>literal_eval</code></p>

<blockquote>
  <p>This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.</p>
</blockquote>

<pre><code>import ast

_dict = {}

with open('file.txt', 'r') as f:
    for line in f.readlines():
        if line.strip():
            key, value = line.split(',')
            value = value.strip()
            try:
                _dict[key] = ast.literal_eval(value)
            except ValueError:
                _dict[key] = value

print _dict
</code></pre>

python type-conversion