1

我有以下代码:

datedict = defaultdict(set)
with open('d:/info.csv', 'r') as csvfile:
    filereader = csv.reader(csvfile, 'excel')

    #passing the header
    read_header = False
    start_date=date(year=2009,month=1,day=1)
    #print((seen_date - start_date).days)
    tdic = {}
    for row in filereader: 
        if not read_header:
            read_header = True
            continue

# reading the rest rows
        name,id,firstseen = row[0],row[1],row[3]
        try:
            seen_date = datetime.datetime.strptime(firstseen, '%d/%m/%Y').date()               
            deltadays = (seen_date-start_date).days
            deltaweeks = deltadays/7 + 1
            key = name +'-'+id
            currentvalue = tdic.get(key, [])
            currentvalue.append(deltaweeks)
            tdic[key] = currentvalue

        except ValueError:
            print('Date value error')
            pass

tdic = dict((name, max(weeks) - min(weeks) + 1) for name, weeks in tdic.iteritems())

pprint.pprint(tdic)

我得到以下结果:

{'Mali-2': 20,
 'Gooki-3': 6,
 'Piata-4': 6,     
 'Goerge-5': 4,
 'Samoo-6': 1,
 'Marria-7': 2}

现在我想将三个项目、名称、id 和周作为单独的列写入 excel 文件中并打印出来。任何人都知道这怎么可能?

4

2 回答 2

3
>>> with open('out.csv', 'w') as f:
        w = csv.writer(f)
        for k, v in tdic.iteritems():
            name, id_ = k.split('-')
            weeks = v
            w.writerow([name, id_, weeks])


>>> with open('out.csv') as f:
        print f.read()


Piata,4,6    
Mali,2,20    
Goerge,5,4    
Gooki,3,6    
Samoo,6,1    
Marria,7,2

但是,我不喜欢您这样做的方式,以下是对您的代码的一些建议:

key = name +'-'+id

不要使用字符串操作来创建密钥,而是使用tuple

key = (name, id)

更改此行:

tdic = dict((name, max(weeks) - min(weeks) + 1) for name, weeks in tdic.iteritems())

只是说

tdic = dict((key, max(weeks) - min(weeks) + 1) for key, weeks in tdic.iteritems())

因为现在它是(name, id_)我们应该反映的关键(这是一件小事但很重要)

那么上面的代码就是

>>> with open('out.csv', 'w') as f:
        w = csv.writer(f)
        for (name, id_), weeks in tdic.iteritems():
            w.writerow([name, id_, weeks])
于 2013-04-21T10:17:43.067 回答
1

您可以像这样定义dict的dict:

a_dict = {key: { anotherKey: value}}

或者如果字典已经存在:

a_dict[key] = {anotherkey: value}
print a_dict[key][anotherkey]
于 2013-04-21T10:11:02.797 回答