简体   繁体   English

将逗号分隔的.txt文件转换为字典

[英]Converting comma separated .txt file into dictionary

I have a comma delimited .txt file and I need to convert the list into key:value pairs in python 3: 我有一个逗号分隔的.txt文件,我需要将列表转换为python 3中的key:value对:

Below is the .txt file: 下面是.txt文件:

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: 这是我的python代码:

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? 我究竟做错了什么?

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: 您可以使用csv.reader将行读入两个项目列表的序列中,以便将其传递给dict构造函数以构建您要查找的dict:

with open("annual_chesapeakeCapital_diversifiedProgramLV.txt") as infile:
    answer = dict(csv.reader(infile))

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. 具体回答你的问题,你在做什么错是readline()只读取一条线-你需要重复读取所有的线条和分裂他们每个人,并使用每个分割的结果来创建字典中的条目。

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? 根据定义,BTW词典的每个键只能有一个条目,因此您是否计划了如果逗号前两行具有相同的值会发生什么情况?

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM