【问题标题】:Openpyxl - looking for best option to get this list, dictionaries thing sortedOpenpyxl - 寻找获得此列表的最佳选择,对字典进行排序
【发布时间】:2021-01-12 19:38:23
【问题描述】:

我有一个带有标题(学生、排名、城市、兴趣)的 JSON 文件。 这是JSON文件的结构

[{"Student": "A", "Rank": 9, "City": “Milan”, "Interest": “Singing”}, {"Student": "B", "Rank": 5, "City": “NYC”, "Interest": “Problem Solving”}, {"Student": "C", "Rank": 9, "City": “Chicago”, "Interest": “Dancing”}, {"Student": "D", "Rank": 10, "City": “Boston”, "Interest": “Parasailing”}, {"Student": "E", "Rank": 9, "City": “Paris”, "Interest": “Apparel Designing”}, {"Student": "F", "Rank": 6, "City": “LA”, "Interest": “Wellness”}, {"Student": "G", "Rank": 25, "City": “Phoenix”, "Interest": “Acting”}]

我在我的代码中像这样打开这个 JSON 文件

jsonfile = open("C:\\Users\Ricky\\Desktop\\StudData.json","rt")
storejsondata = json.load(jsonfile)

storejsondata 给了我这样的字典列表 [{'Student': 'A', 'Rank': 9, 'City': 'Milan', 'Interest': 'Singing'}, {'Student': 'B', 'Rank': 5, 'City': 'NYC', 'Interest': 'Problem Solving'} ....]

然后我遍历这个列表,像这样

for dictdata in storejsondata:
    print(dictdata)
print(type(dictdata))

它像这样垂直显示列表中的各个字典 {'学生':'A','排名':9,'城市':'米兰','兴趣':'唱歌'} {“学生”:“B”,“排名”:5,“城市”:“纽约”,“兴趣”:“解决问题”) ...... 我想得到这个的钥匙,我愿意:

listkey=[]
for key in xdict.keys():
     print(f'keys are: {key}')
     listkey.append(key)
print(listkey)
I write the keys as header in Excel like this
wb=openpyxl.load_workbook("C:\\Users\Rickey\\Desktop\\Studrec.xlsx")
sheet=wb.active
rows = 1
cols = 1
for i in range (0,len(listkey)):
     sheet.cell(row=rows,column=cols).value=listkey[i]
     cols=cols+1

wb.save("C:\\Users\Ricky\\Desktop\\Studrec.xlsx")

我可以在 Excel 中的第 1 行写标题。这很好用。

问题:

  1. 如何获取值? 如果我使用:

    对于 key, val in datadict.items(): 打印(键,值)

这仅显示最后一个字典项的值,即 G、25、Phoenix、Acting。如何获取所有字典的值 2. 如何在 Excel 中写入这些值?我想要这样- 第 1 行 Col 1、Col2、Col3、Col 4 是标题 从第 2 行开始,我想要相应列中的值。如何使用 Openpyxl 获得这个?

【问题讨论】:

  • 一定要用excel吗? csv格式可以吗?
  • Excel 更可取。如果 CSV 格式有更简单更好的解决方案,我可以试试这个。谢谢!
  • csv 更简单,你可以只使用标准 python 库,然后你可以在 excel 中打开它,你也可以使用 pandas

标签: python json excel list dictionary


【解决方案1】:

如果 openpyxl 不是绝对要求,您可以通过使用 python 标准库(csvjson)并写入 csv 或使用 pandas 并写入 excel(或几乎任何其他文件)来真正简化此操作格式):

标准库:

import json
import csv

# function to read json files into a dict or list of dicts
def read_json(path):
    with open(path, 'r') as file:
        return json.load(file)

# function to write csv files from dicts or list of dicts
def write_csv(data, path):
    with open(path, 'w') as file:
        fieldnames = set().union(*data)
        writer = csv.DictWriter(file, fieldnames=fieldnames, lineterminator='\n')
        writer.writeheader()
        writer.writerows(data)

# load the json data
json_data = read_json('StudData.json')

write_csv(json_data, './student_data.csv')

熊猫:

import pandas as pd

df = pd.read_json('./StudData.json')
df.to_excel('./student_data.xlsx')

输出(excel截图):

【讨论】:

  • 非常感谢!我会尝试这两种选择。比起 pandas,我更喜欢标准的 Python 库,但很高兴知道它的逻辑如此简单易懂!
  • 我试过这两个程序,效果很好。不过有一个问题 - 我不太明白这个 fieldnames = set().union(*data) .. @Tenacious B
  • 该行包含所有可能的列标题,请参阅geeksforgeeks.org/union-function-python
猜你喜欢
  • 2018-12-16
  • 1970-01-01
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多