[英]How to specify type of key, value pair in dictionary
I'm trying to print out a dictionary in the following format. 我正在尝试以以下格式打印字典。 I want to do this because I need to print out a bar graph in D3 using the JSON format. 我想这样做是因为我需要使用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
}
]
Currently, I have it like [ {'Wyoming': 630, 'Alaska': 1617}]
. 目前,我喜欢[ {'Wyoming': 630, 'Alaska': 1617}]
。 How do I do turn it into the above format? 如何将其转换为以上格式? I have added it to a list because I also need the dictionary in an array. 我将其添加到列表中是因为我还需要数组中的字典。
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)
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))
collections.Counter
, json.dumps
collections.Counter
, json.dumps
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.