如何在字典中创建字典

时间:2013-04-21 10:06:04

标签: python excel fwrite

我有以下代码:

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}

现在我想在excel文件中编写并打印三个项目,name,id和weeks作为单独的列。谁知道怎么可能?

2 个答案:

答案 0 :(得分: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])

答案 1 :(得分:1)

你可以像这样定义一个dict的词典:

a_dict = {key: { anotherKey: value}}

或者如果dict已经存在:

a_dict[key] = {anotherkey: value}
print a_dict[key][anotherkey]