【问题标题】:Printing out nested dictionary in specific format and outputting to json file以特定格式打印嵌套字典并输出到 json 文件
【发布时间】:2019-09-24 13:57:06
【问题描述】:

我正在尝试按以下格式打印字典。我想这样做是因为我需要使用 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": {"Wyoming": 245, "Alaska": 533} 等。

这是我正在使用的 xlsx 文件

【问题讨论】:

    标签: javascript node.js python-3.x dictionary d3.js


    【解决方案1】:

    因为这是您处理 freq 变量的方式。

    key = {currDecade:{currState: 1}}
    

    这将转化为:

    {"1980":{"California":1}}
    

    如果您将该行和其他分支更改为类似的内容,您应该会得到您期望的输出。

    {currDecade:{"State":currState, "Freq":1}}
    

    【讨论】:

    • 这实际上并没有给我预期的输出。
    猜你喜欢
    • 1970-01-01
    • 2021-04-09
    • 2020-08-27
    • 1970-01-01
    • 2021-06-01
    • 2020-09-14
    • 2017-05-14
    • 1970-01-01
    • 2018-02-02
    相关资源
    最近更新 更多