Reputation: 71
I have a comma delimited .txt file and I need to convert the list into key:value pairs in python 3:
Below is the .txt file:
1988,0.4891
1989,0.2830
1990,0.4312
1991,0.1251
1992,0.0181
1993,0.6182
1994,0.1587
1995,0.1409
1996,0.1505
1997,0.0994
1998,0.1631
1999,0.0330
2000,0.0523
2001,-0.0798
2002,0.1107
2003,0.2308
2004,0.0484
2005,0.0114
2006,0.1088
2007,0.0228
2008,0.1538
2009,0.0038
2010,0.1085
2011,-0.0631
2012,-0.1581
2013,0.2538
2014,0.1377
2015,0.0199
2016,-0.0392
2017,0.0433
2018,-0.0154
Here is my python code:
import csv
answer = {}
with open("annual_chesapeakeCapital_diversifiedProgramLV.txt") as infile:
keys = infile.readline().split(",")
values = infile.readline().split("\n")
answer = dict(zip(keys, values))
print(answer)
What am I doing wrong?
Upvotes: 2
Views: 2417
Reputation: 1254
With pandas it's easy
import pandas as pd
df=pd.read_csv("annual_chesapeakeCapital_diversifiedProgramLV.txt",header=None)
answer =dict(zip(df[0].values,df[1].values))
Upvotes: 0
Reputation: 6826
To specifically answer your question, what you are doing wrong is that readline()
only reads one line - you need to iterate reading all the lines and splitting each of them, and using the result of each split to create entries in the dictionary.
BTW dictionaries can by definition only have one entry for each key, so have you planned what will happen if two lines have the same value before the comma?
Upvotes: 2
Reputation: 106618
You can use csv.reader
to read the rows into a sequence of two-item lists, so that you can pass it to the dict constructor to build the dict you're looking for:
with open("annual_chesapeakeCapital_diversifiedProgramLV.txt") as infile:
answer = dict(csv.reader(infile))
Upvotes: 3