我有多个这样的词典,其中的键是年龄,值是该年龄的人数。然后将它们分为多个词典
age_50 = {39: 66, 40: 83, 42: 217, 43: 53, 23: 33, 21: 28}
age50_80 = {59: 397, 65: 408, 61: 120, 67: 241, 68: 372, 78: 424, 76: 635 }
age_80 = {80: 93, 88: 425, 83: 165, 84: 58, 91: 88}
我想将其写入CSV文件,其方式是每一列都是字典,而行是每个键的值。我希望我的输出是下表。如果键存在,则写入值。如果不是,只需填写0:
Age_Under50 Between_50_80 Greater_80
66 397 0
83 408 93
217 120 425
53 241 0
33 372 165
28 424 58
0 635 88
答案 0 :(得分:1)
尝试以下类似方法
if (scan.ioException() != null) {
throw scan.ioException();
}
对于Windows
import csv, itertools
age_50 = {39: 66, 40: 83, 42: 217, 43: 53, 23: 33, 21: 28}
age50_80 = {59: 397, 65: 408, 61: 120, 67: 241, 68: 372, 78: 424, 76: 635 }
age_80 = {80: 93, 88: 425, 83: 165, 84: 58, 91: 88}
cf = csv.writer(open("test.csv", "w"))
cf.writerows(
itertools.zip_longest(
['Age_Under50'] + [age_50.get(k, 0) for k in range(50)],
['Between_50_80'] + [age50_80.get(k, 0) for k in range(50,80)],
['Greater_80'] + [age_80.get(k, 0) for k in range(80,100)],
fillvalue=0
)
)