我正在尝试以以下格式打印字典。我想这样做是因为我需要使用JSON格式在D3中打印出条形图。
[
{
"Month": "January",
"Freq": 52928
},
{
"Month": "March",
"Freq": 51444
},
{
"Month": "April",
"Freq": 51209
},
{
"Month": "May",
"Freq": 53394
},
{
"Month": "June",
"Freq": 53662
},
{
"Month": "July",
"Freq": 58696
},
{
"Month": "August",
"Freq": 58072
},
{
"Month": "December",
"Freq": 55187
},
{
"Month": "November",
"Freq": 50016
},
{
"Month": "February",
"Freq": 46079
},
{
"Month": "October",
"Freq": 53650
},
{
"Month": "September",
"Freq": 54117
}
]
目前,我喜欢[{'Wyoming': 630, 'Alaska': 1617}]
。如何将其转换为以上格式?我将其添加到列表中是因为我还需要数组中的字典。
xl = pd.ExcelFile('Wyoming.xlsx')
df = xl.parse("Sheet1")
statesDict1 = dict()
allStates = df["State"]
for key in allStates:
if key in statesDict1:
statesDict1[key] += 1
else:
s = {key:1}
statesDict1.update(s)
#print(statesDict)
statesDict = list()
statesDict.append(statesDict1)
# file = open("MurderRateState.js", "w+")
# file.write(json.dumps(statesDict))
# file.close()
print(statesDict)
答案 0 :(得分:1)
import collections
import json
class OrderedCounter(collections.Counter, collections.OrderedDict):
"""Counter that remembers the order elements are first encountered."""
pass
month_frequencies = OrderedCounter(df['Month']).items()
output_dicts = [{'Month': m, 'Freq': f} for m, f in month_frequencies]
print(json.dumps(output_dicts))