为Dict保存不同的键并根据字典Python

时间:2017-05-22 11:16:49

标签: python list dictionary

我想以示例输出中显示的字典格式保存当前的示例数据。可能有各种方法可以这样做。我想学习所有方法

dict应该是{月:同月的出生总数}

  

工作的示例数据

['year,month,date_of_month,day_of_week,births', '1994,1,1,6,8096', '1994,1,2,7,7772', '1994,1,31,1,10765', '1994,2,1,2,11755', '1994,2,2,3,11483', '1994,2,3,4,11523', '1994,2,27,7,8195', '1994,2,28,1,11091', '1994,3,29,2,12154', '1994,3,30,3,11540', '1994,3,31,4,11782', '1994,4,1,5,10630', '1994,4,2,6,8782' '1994,4,14,4,11709', '1994,4,15,5,11753', '1994,4,28,4,11527']

  

需要样品输出
  需要{month:births}#births =适当月份的出生总数。

{ 1: 3232517, 2: 3018140, 3: 3322069, 4: 3185314, 5: 3350907, 6: 3296530, 7: 3498783, 8: 3525858, 9: 3439698, 10: 3378814, 11: 3171647, 12: 3301860 }
感谢帮助。

2 个答案:

答案 0 :(得分:1)

使用默认整数的defaultdict。然后,您需要遍历数据,拆分逗号,并将最后一列添加到dict中的相关键。

from collections import defaultdict
output = defaultdict(int)
for row in data[1:]:
    r = row.split(',')
    output[int(r[1])] += int(r[4])

答案 1 :(得分:0)

    data = ['year,month,date_of_month,day_of_week,births',
 '1994,1,1,6,8096',
 '1994,1,2,7,7772',
 '1994,1,31,1,10765',
 '1994,2,1,2,11755',
 '1994,2,2,3,11483',
 '1994,2,3,4,11523',
 '1994,2,27,7,8195',
 '1994,2,28,1,11091',
 '1994,3,29,2,12154',
 '1994,3,30,3,11540',
 '1994,3,31,4,11782',
 '1994,4,1,5,10630',
 '1994,4,2,6,8782',
 '1994,4,14,4,11709',
 '1994,4,15,5,11753',
 '1994,4,28,4,11527']

myDict = {}

for item in data[1:]:
  year,month,date_of_month,day_of_week,births = item.split(',')
  myDict[month] = myDict.get(month,0)+int(births)

print(myDict)

=============================================== ======

myDict = {}

for item in data[1:]:
  year,month,date_of_month,day_of_week,births = item.split(',')
  if month not in myDict:
    myDict[month] = 0 
  myDict[month] += int(births)
print(myDict)