-2

So I have a data.txt file that holds information about a car:

CAR|PRICE|RPM

TOYOTA|21,000|3,600

HONDA|19,000|4,000

And by passing this data file into the function createCarDictionary I was able to create a dictionary that creates the car brand as the key and the values as the remaining information in the txt file stored as tuples:

dict1 = {}

def createCarDictionary(datafile):
    for line in datafile.splitlines():
        key, value, value2 = map(str.strip, line.split('|'))
        dict1[key] = value, value2
    return dict1

datafile = open('data.txt', 'r').read()

createCarDictionary(datafile)
print(dict1)

OUTPUT

{'CAR': ('PRICE', 'RPM'), 'TOYOTA': ('21,000', '3,600'), 'HONDA': ('19,000', '4,000')}

So my question(s) is/are: What must I add to the function to 1) remove the commas in the numbers and 2) convert the tuple values into a list, so I can manipulate them later.

Community
  • 1
  • 1
CosmicCat
  • 612
  • 9
  • 19
  • https://stackoverflow.com/questions/1779288/how-do-i-use-python-to-convert-a-string-to-a-number-if-it-has-commas-in-it-as-tho – MFisherKDX Nov 29 '18 at 20:54

2 Answers2

0

You could simply surround your values with brackets to make them a list instead of tuple, and use replace() to remove all ',' from every line.

dict1 = {}

def createCarDictionary(datafile):
    for line in datafile.splitlines():
        line = line.replace(',', '')
        key, value, value2 = map(str.strip, line.split('|'))
        dict1[key] = [value, value2]
    return dict1

datafile = open('data.txt', 'r').read()

createCarDictionary(datafile)
print(dict1)

Output:

{'HONDA': ['19000', '4000'], 'TOYOTA': ['21000', '3600'], 'CAR': ['PRICE', 'RPM']}
Filip Młynarski
  • 3,534
  • 1
  • 10
  • 22
0

One way, change:

dict1[key] = value, value2

To:

dict1[key] = [int(i.replace(',','')) for i in (value1,value2)]


But you could also use pandas if you are open to new libraries:

import pandas as pd

filedata = '''\
CAR|PRICE|RPM
TOYOTA|21,000|3,600
HONDA|19,000|4,000'''

fileobj = pd.compat.StringIO(filedata) # change this to the path of your file
df = pd.read_csv(fileobj, sep='|', thousands=',')
d = dict(zip(df.pop('CAR'), df.values.tolist()))
#d = df.set_index('CAR').to_dict('i') # OR MAYBE THIS?
print(d)

Returns:

{'TOYOTA': [21000, 3600], 'HONDA': [19000, 4000]}
Anton vBR
  • 18,287
  • 5
  • 40
  • 46