如何在Python中使用CSV文件创建动态字典

2024-06-16 12:59:07 发布

您现在位置:Python中文网/ 问答频道 /正文

问题很简单,我有一个CSV文件,其中有四列,我想为第一列赋值,并在python脚本中将其放入字典中。我不想在字典中添加任务完成日期的值。在

在一个名为VC.csv版,例如:

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

我想要的最终结果是,当我打印字典时,它们是这样的。在

例如

^{pr2}$

我的问题是尝试循环槽,并在已经定义好的字典中添加更多内容。我猜我不是在追加,而是在每次循环中重新创建和重写循环。结果我得到的结果是{'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

Tags: andcsvin字典companyreplaceenergyseries
2条回答

我想这段代码可以汇总您的公司数据,只需通过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

我想您只需要一个字典(不是很多),这样您就可以按公司名称查找数据,例如:

^{pr2}$

输出:

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']]

字典条目的值是一个事件列表,每个事件都是一个列表,首先是类型,然后是日期。在

相关问题 更多 >