python - putting int/float from file into a dictionary -


i put values csv file dict. example is:

type, weldline  diam, 5.0  num of elems, 4 

and end after reading dictionary (for later use in api) in:

 {'type':'weldline' , 'diam':'5.0','num of elems':'4'} 

since api expects dictionary provided necessary keywords 'type', 'diam', ... according api doc.

the problem have is, api expects float diam , integer num of elems

since have large number of entries: there simple automatic way string conversion float or int? or have write on own?

you can use literal_eval

this can used safely evaluating strings containing python values untrusted sources without need parse values oneself. not capable of evaluating arbitrarily complex expressions, example involving operators or indexing.

import ast  _dict = {}  open('file.txt', 'r') f:     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 

Comments