以易于编辑和读取的方式将嵌套字典导入和导出到Excel

时间:2015-09-14 13:35:24

标签: python excel dictionary

我试图导出字典,格式为:

d = {'Apple':{'Weight':12,'Colour':'red'},
     'Banana':{'Weight':11,'Colour':'yellow','Bunched':1}        
    }

到excel文件,格式为:

NAME    Weight  Colour  Bunched
Apple   12      red
Banana  11      yellow  1

d中的每个键都不具有相同数量的键。

我设法获得了导入代码,但我在导出代码方面遇到了问题。到目前为止,我已经得到了这个:

   import csv
    data = Fruits
    with open('fruits.csv', 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            a = iter(row[1:])
            data[row[0]] = dict(zip(a, a))
    data = Vegetables
    with open('veg.csv', 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            a = iter(row[1:])
            data[row[0]] = dict(zip(a, a))

但它不起作用。有什么帮助吗?

2 个答案:

答案 0 :(得分:3)

您可以像这样使用csv.DictWritercsv.DictReader

import csv

d = {'Apple':{'Weight': 12,
              'Colour': 'red'},
     'Banana':{'Weight': 11,
               'Colour': 'yellow',
               'Bunched': 1}}

fieldnames = ["name", "Weight", "Colour", "Bunched"]

with open("fruits.csv", "w") as f:
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    for fruit, fruit_info in d.items():
        row = fruit_info
        row.update({"name": fruit})
        writer.writerow(row)

with open('fruits.csv', 'r') as f:
    reader = csv.DictReader(f, fieldnames=fieldnames)
    ret_d = {}
    for row in reader:
        fruit = {}
        for key, value in row.items():
            if not key == "name" and value:
                fruit[key] = value
        ret_d[row["name"]] = fruit
    print(ret_d)

使用此解决方案,您需要展平字典,因为csv.DictWriter使用以下模式的字典写入每一行:

{column1: data, column2: data, column3: data, ...}

你必须给出字段名,因为字典是无序的。

有关详细信息,请参阅the docs

答案 1 :(得分:2)

您可以使用pandas from_dict()轻松完成此操作:

import pandas as pd

d = {'Apple':{'Weight':12,'Colour':'red'},
     'Banana':{'Weight':11,'Colour':'yellow','Bunched':1}
    }

df = pd.DataFrame.from_dict(d, orient='index') # convert dict to dataframe

df.to_csv('fruits.csv') # write dataframe to file