Reputation: 13
I have a data file that contains what need to become the keys and entries in a dictionary. I will be reading and writing the entries and reading the keys. I have found similar things explained elsewhere on stackoverflow but for the life of my cannot make sense of it. any help is more than welcome!
engine oil/filter : 6000
transmission fluid : 48000
timing belt : 96000
other belts : 96000
brake fluid : 48000
air filter : 48000
spark plugs : 96000
rear differential : 48000
Above is the data file that needs to be read into a dictionary below is the dictionary it needs to end up in.
service_intervals = {'engine oil/filter' : 6000 , 'transmission fluid' : 48000 , 'timing belt' : 96000 ,
'other belts' : 96000 , 'brake fluid' : 48000 , 'air filter' : 48000 ,
'spark plugs' : 96000 , 'rear differential' : 48000}
what sort of algorithm or functions could i use to make this happen?
EDIT: from sleuthing tells me that something to do with ast.literal_eval may be the best solution, but I'm having trouble understanding it.
Upvotes: 1
Views: 111
Reputation: 129011
You don't need ast.literal_eval
. Just read line by line, split
on :
, strip
, parse the integers, and put the values into the dictionary:
my_dict = {}
with open('some file.txt', 'r') as f:
for line in f:
key, value = line.split(':')
my_dict[key.strip()] = int(value)
Upvotes: 5