-1

I have code like this

def some_data():

    file_data = open(r"some.txt","r")

    result = {}
    for line in file_data:
        values = line.split(sep="\t")
        if values[-1][-1:] == "\n":
            values[-1] = values[-1][:-1]
        else:
            values[-1] = values[-1]
        result.update({values[0]: [values[1], values[2],values[3], values[4]]})

    return result

That gives me output:

{'130121322X': ['90', '50', '40', '60'], '130121323Y': ['80', '70', '60', '60'], '130121325X': ['100', '90', '75', '50'], '130121334Y': ['90', '90', '80', '85'], '130121337Z': ['95', '60', '70', '80'], '130121338X': ['50', '50', '40', '60']}

How can I convert the multiple values to integers? So should like this i.e:

{'130121322X': [90, 50, 40, 60], '130121323Y': [80, 70, 60, 60], '130121325X': [100, 90, 75, 50], '130121334Y': [90, 90, 80, 85], '130121337Z': [95, 60, 70, 80], '130121338X': [50, 50, 40, 60]}
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

Now there's a bunch of parentheses, but...

d = {
    '130121322X': ['90', '50', '40', '60'], 
    '130121323Y': ['80', '70', '60','60'], 
    '130121325X': ['100', '90', '75', '50'], 
    '130121334Y': ['90', '90', '80', '85'], 
    '130121337Z': ['95', '60', '70', '80'], 
    '130121338X': ['50', '50', '40', '60']
}

dict(map(lambda x: (x[0],list(map(int,x[1]))),d.items()))

Also, it seems like you have a file with columns, separated by '\t'. You might use pandas.read_csv. It works with .txt files just fine and gives you a DataFrame, that lets you operate with your data functionally. Check read_csv and the guide
Let's say, you have a .txt file like

some    2   3   4
random  6   7   8
text    10  11  12

You can use

import pandas as pd
df = pd.read_csv('path/to/txt',sep='\t', 
                 names=['col1','col2','col3','col4'])
print(df)

to get a data frame

     col1  col2  col3  col4
0    some     2     3     4
1  random     6     7     8
2    text    10    11    12

Also, all the integers are already read as integers

bottledmind
  • 603
  • 3
  • 10