【问题标题】:How to write an excel file which has dictionary keys as column name and dictionary values as column values?如何编写一个将字典键作为列名,将字典值作为列值的excel文件?
【发布时间】:2020-01-23 07:26:12
【问题描述】:

我有一本字典如下:

[{'tarih': '01.02.2019', '4980': 1.1517482514, '2738': 0.9999999999999999, '0208': 1.0102518747365854},{'tarih': '02.02.2019', '4980': 1.1517486767, '2738': 0.9999999999999999, '0208': 1.0102518747368554}]

我想写一个excel文件,比如:

tarih          4980           2738                   0208               // dictionary keys as column name
01.02.2019     1.1517482514   0.9999999999999999     1.0102518747365854 // dict values as value
02.02.2019     1.1517486767   0.9999999999999999     1.0102518747368554 // dict values as value

【问题讨论】:

    标签: python django excel dictionary


    【解决方案1】:

    您可以使用pandas 模块来做到这一点

    import pandas as pd
    
    x = [{'tarih': '01.02.2019', '4980': 1.1517482514, '2738': 0.9999999999999999, '0208': 1.0102518747365854},{'tarih': '02.02.2019', '4980': 1.1517486767, '2738': 0.9999999999999999, '0208': 1.0102518747368554}]
    
    df = pd.DataFrame(x)
    
    df.to_excel ('test.xlsx', sheet_name = 'sheet1', index = False)
    

    输出:

         tarih      4980        2738    0208
    0   01.02.2019  1.151748    1.0    1.010252
    1   02.02.2019  1.151749    1.0    1.010252
    

    【讨论】:

    • 谢谢@AkshayNevrekar。我一起使用了 df.to_excel ('test.xlsx', sheet_name = 'sheet1', index = False)。我创建了我想要的文件。
    【解决方案2】:
    import csv
    with open('dict.csv', 'w', newline="") as csv_file:  
        writer = csv.writer(csv_file)
        for key, value in mydict.items():
           writer.writerow([key, value])
    

    【讨论】:

    • 这将在每个条目中写入一个 row,其中第一列中的键和第二列中的值。他们要求的是作为列标题的键和作为行值的值。 csv.DictWriter 基本上是做什么的。
    • @Masklinn 是的,你是对的。这将在每个条目中写入一行,第一列中的键和第二列中的值。我想使用字典键作为列名字典值作为值。
    • 我更新了问题以便更好地理解 .@Masklinn 和 @Yeganeh Salami
    猜你喜欢
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    相关资源
    最近更新 更多