0

I like to put some values from a csv file into a dict. An example is:

TYPE, Weldline

Diam, 5.0

Num of Elems, 4

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

 {'TYPE':'Weldline' , 'Diam':'5.0','Num of Elems':'4'}

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

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

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?

Mathias711
  • 6,568
  • 4
  • 41
  • 58

3 Answers3

1

You can use literal_eval

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.

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
turkus
  • 4,637
  • 2
  • 24
  • 28
0

Also try this it seems more simple.

import csv,ast
    with open('file.csv', mode='r') as file:
    reader = csv.reader(file)
    mydict = {rows[0]:ast.literal_eval(rows[1]) for rows in reader}
print mydict
florex
  • 943
  • 7
  • 9
0

Now I tried this:

                key   = Line[0].strip()
                value = Line[1].strip()
                try:
                    value = int(Line[1].strip())
                except ValueError:
                    try: 
                        value = float(Line[1].strip())
                    except ValueError:
                        value = Line[1].strip()

            Entry[key]=value            

It seems it works fine...