![](/img/trans.png)
[英]How can I create a dictionary within another dictionary with count capability?
[英]How can I create dictionary within dictionary
我有以下代碼:
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作為單獨的列。 誰知道怎么可能?
>>> 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])
你可以像這樣定義一個dict的dict:
a_dict = {key: { anotherKey: value}}
或者如果dict已經存在:
a_dict[key] = {anotherkey: value}
print a_dict[key][anotherkey]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.