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.

[
  {
    "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}]. 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)

Dataset

1 Answers

1
Brian Rodriguez On Best Solutions
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