我正在尝试以以下格式打印字典。我想这样做是因为我需要使用JSON格式绘制D3中的一些趋势。对于这种趋势,我计算了每个州(1980年代至2010年代)在每个州的谋杀案数量。
我能够输出文件和所有内容,但是由于我试图创建图形,因此在标记文件中字典中的每个键,值对方面,JSON文件中的数据格式必须非常具体。输出。
xl = pd.ExcelFile('Murders.xlsx')
df = xl.parse('Sheet1')
year = df['Year']
state = df['State']
freq = dict()
for i in range(0, len(df)):
currYear = year.iloc[i]
if(currYear >= 1980 and currYear < 1989):
currDecade = 1980
elif(currYear >= 1990 and currYear < 2000):
currDecade = 1990
elif(currYear >= 2000 and currYear < 2010):
currDecade = 2000
elif(currYear >= 2010):
currDecade = 2010
currState = state.iloc[i]
if currDecade in freq:
if currState in freq[currDecade]:
freq[currDecade][currState] += 1
else:
key = {currState: 1}
freq[currDecade].update(key)
else:
key = {currDecade:{currState: 1}}
freq.update(key)
#print(freq)
file = open("MurderRateDecState.js", "w+")
file.write(json.dumps(freq))
file.close()
我希望输出为[{“ Decade”:“ 1980”,“ State”:[{“ State”:“ California”,“ Freq”:29591},{“ State”:“ Massachusetts”,“频率”:1742},...}]
但是我得到了{“ 1980”:{“怀俄明州”:245,“阿拉斯加”:533},等等。
答案 0 :(得分:0)
因为那是您处理freq变量的方式。
key = {currDecade:{currState: 1}}
那将转化为:
{"1980":{"California":1}}
如果将那条线和其他分支更改为类似的内容,则应该获得期望的输出。
{currDecade:{"State":currState, "Freq":1}}