如何使用CSV文件在Python中创建动态词典
问题很简单,我有一个包含四列的CSV文件,我想计算第一列的值,并将其放入python脚本中的字典中。我不想在字典中添加任务完成日期的值 在名为VC.CSV的文件中可以找到该文件的CSV数据,例如:如何使用CSV文件在Python中创建动态词典,python,python-2.7,csv,dictionary,append,Python,Python 2.7,Csv,Dictionary,Append,问题很简单,我有一个包含四列的CSV文件,我想计算第一列的值,并将其放入python脚本中的字典中。我不想在字典中添加任务完成日期的值 在名为VC.CSV的文件中可以找到该文件的CSV数据,例如: 24M技术,A系列,2010年8月19日 2400万技术,赠款,2010年8月16日 2B能源、私募股权,2014年3月18日 2B能源,B系列,2014年3月18日 2B能源,未分配VC,2008年5月1日 3G太阳能光伏,A系列,12/17/12 3阳光集团,成长股权,2014年3月3日 3梯组,
24M技术,A系列,2010年8月19日
2400万技术,赠款,2010年8月16日
2B能源、私募股权,2014年3月18日
2B能源,B系列,2014年3月18日
2B能源,未分配VC,2008年5月1日
3G太阳能光伏,A系列,12/17/12
3阳光集团,成长股权,2014年3月3日
3梯组,C系列,2008年11月17日
我想要的最终结果是,当我打印字典时,它们是这样的
比如说
>>> print 3TierGroup
>>>
>>>{'company': '2B Energy', 'Private Equity': '3/18/14', 'Series B': '3/18/14', 'Unattributed VC': '05/01/08'}
我的问题是尝试循环槽,并向已定义的字典添加更多内容。我猜我不是在追加,而是在每次传递时重新创建和覆盖循环。我得到的结果是{'company':'2B Energy','Private Equity':'3/18/14'}
我需要代码的最后一行来测试字典是否已经存在;如果是这样的话,它将附加额外的四舍五入日期
这是我的密码
import csv
companyList =[]
transactionDates=[]
dictNames=[]
def fileNameCleaner(namer):
namer = namer.replace(' ', '')
namer = namer.replace(',','')
namer = namer.replace('-','')
namer = namer.replace('.','')
namer = namer.replace('_','')
namer = namer.replace('@','')
namer = namer.replace('&','')
return namer
with open('VC.csv', 'rb') as rawData:
timelineData = csv.reader(rawData, delimiter=',', quotechar='"') # Open CSV file and snag data
for line in timelineData: # Run through each row in csv
companyList.append(fileNameCleaner(line[0])) # Create list and remove some special charcters
companyList = list(set(companyList)) # Remove duplicates and Sort
for companyListRow in companyList:
with open('VC.csv', 'rb') as rawDataTwo:
timelineDataTwo = csv.reader(rawDataTwo, delimiter=',', quotechar='"')
for TList in timelineDataTwo:
company = TList[0]
finRound = TList[1]
tranDate = TList[2]
if companyListRow == fileNameCleaner(TList[0]):
companyListRow = {'company':TList[0], finRound:tranDate }
print companyListRow
我认为此代码将汇总您的公司数据,只需一次通过CSV:
# define dict (to be keyed by company name) to accumulate company attributes from CSV file
company_data = {}
with open('VC.csv', 'rb') as rawData:
# Open CSV file and snag data
timelineData = csv.DictReader(rawData, delimiter=',', quotechar='"',
fieldnames=['company','key','value'])
# Run through each row in csv
for line in timelineData:
name = filenameCleaner(line['company'])
# get record for previously seen company, or get a new one with just the name in it
rec = company_data.get(name, {'company': name})
# add this line's key-value to the rec for this company
rec[line['key']] = line['value']
# stuff updated rec back into the overall summarizing dict
company_data[name] = rec
# now get the assembled records by getting just the values from the summarizing dict
company_recs = company_data.values()
读取您的数据:
str1='''24M Technologies,Series A,8/19/10
24M Technologies,Grant,8/16/10
2B Energy,Private Equity,3/18/14
2B Energy,Series B,3/18/14
2B Energy,Unattributed VC,5/1/08
3GSolar Photovoltaics,Series A,12/17/12
3sun Group,Growth Equity,3/3/14
3Tier Group,Series C,11/17/08'''
list1= str1.split('\n')
print list1
我认为您只需要一本词典(不是很多),因此您可以按公司名称查找数据,例如:
comps={}
for abc in list1:
a,b,c=abc.split(',')
if not a in comps:
comps[a]= [[b,c]]
else:
comps[a].append([b,c])
for k,v in comps.iteritems():
print k,v
输出:
3sun Group [['Growth Equity', '3/3/14']]
2B Energy [['Private Equity', '3/18/14'], ['Series B', '3/18/14'], ['Unattributed VC', '5/1/08']]
3Tier Group [['Series C', '11/17/08']]
3GSolar Photovoltaics [['Series A', '12/17/12']]
24M Technologies [['Series A', '8/19/10'], ['Grant', '8/16/10']]
字典条目的值是一个事件列表,每个事件都是一个列表,首先是类型,然后是日期。我认为这种数据最好在SQL数据库(比如SQLite)中表示和查询,因为融资类型(seriesA、serieb等)会经常重复,并占用大量不必要的存储空间。还可以查询数据,找出SQL数据库中最适合提供的资金、顺序(一个表用于公司,一个表用于资金类型,一个表用于外键为公司和资金类型的日期)。