简体   繁体   English

将嵌套字典列表写入python中的excel文件

[英]Write list of nested dictionaries to excel file in python

I have a list of nested dictionaries that looks like this:我有一个嵌套字典列表,如下所示:

[{'posts': {'item_1': 1,
                            'item_2': 8,
                            'item_3': 105,
                            'item_4': 324,
                            'item_5': 313, }},
                 {'edits': {'item_1': 1,
                            'item_2': 8,
                            'item_3': 61,
                            'item_4': 178,
                            'item_5': 163}},
                 {'views': {'item_1': 2345,
                            'item_2': 330649,
                            'item_3': 12920402,
                            'item_4': 46199102,
                            'item_5': 43094955}}]

I would like to write it to an excel file in this format:我想以这种格式将其写入excel文件:

+--------+-------+-------+-----------+
|        | posts | edits |   views   |
+--------+-------+-------+-----------+
| item_1 |     1 |     1 |      2345 |
| item_2 |     8 |     8 |    330649 |
| item_3 |   105 |    61 |  12920402 |
| item_4 |   324 |   178 |  46199102 |
| item_5 |   313 |   163 | 430949955 |
+--------+-------+-------+-----------+

I am using the xlsxwriter library and trying the following and variations on the following without success:我正在使用xlsxwriter库并尝试以下和变体但没有成功:

for item in data:
    for col_name, data in item.iteritems():
        col += 1
        worksheet.write(row, col, col_name)
        for row_name, row_data in data.iteritems():
            col += 1
            worksheet.write(row, col, row_name)
            worksheet.write(row + 1, col, row_data)

I'm wondering if it makes sense to rework my nested dictionary object or is it possible to write to excel in it's current form?我想知道返工我的嵌套字典对象是否有意义,或者是否可以以当前的形式写入 excel?

When I say without much success i mean, that I can get it to write certain thigns to the excel file, like column names or row or the data, but I am unable to get it to write like pictured above.当我说没有多大成功时,我的意思是,我可以让它将某些内容写入 excel 文件,例如列名或行或数据,但我无法让它像上图那样写。 I'm not getting errors, I suspect i jsut don't know how to unpack this object properly to loop through it.我没有收到错误,我怀疑我只是不知道如何正确解压缩这个对象来循环遍历它。 In the code above, I am given a combination of row and column names on row 1 and all of the values on row 2.在上面的代码中,我得到了第 1 行的行名和列名以及第 2 行的所有值的组合。

My output for the code above is:我上面代码的输出是:

+--+-------+--------+--------+--------+--------+--------+-------+--------+--------+--------+--------+--------+-------+----------+----------+--------+----------+--------+
|  | posts | item_4 | item_5 | item_2 | item_3 | item_1 | edits | item_4 | item_5 | item_2 | item_3 | item_1 | views |  item_4  |  item_5  | item_2 |  item_3  | item_1 |
+--+-------+--------+--------+--------+--------+--------+-------+--------+--------+--------+--------+--------+-------+----------+----------+--------+----------+--------+
|  |       |    324 |    313 |      8 |    105 |      1 |       |    178 |    163 |      8 |     61 |      1 |       | 46199102 | 43094955 | 330649 | 12920402 |   2345 |
+--+-------+--------+--------+--------+--------+--------+-------+--------+--------+--------+--------+--------+-------+----------+----------+--------+----------+--------+

As an alternative, this could be solved using csv as follows:作为替代方案,这可以使用csv解决,如下所示:

import csv
import itertools

nested = [
    {'posts': {'item_1': 1, 'item_2': 8, 'item_3': 105, 'item_4': 324, 'item_5': 313,}},
    {'edits': {'item_1': 1, 'item_2': 8, 'item_3': 61, 'item_4': 178, 'item_5': 163}},
    {'views': {'item_1': 2345, 'item_2': 330649, 'item_3': 12920402, 'item_4': 46199102, 'item_5': 43094955}}]

headings = [d.keys()[0] for d in nested]
entries = [sorted(nested[index][col].items()) for index, col in enumerate(headings)]    

with open('output.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(['items'] + headings)

    for cols in itertools.izip_longest(*entries, fillvalue=['<n/a>']*len(entries[0])):
        csv_output.writerow([cols[0][0]] + [col[1] for col in cols])

This would give you output.csv as follows:这会给你output.csv如下:

items,posts,edits,views
item_1,1,1,2345
item_2,8,8,330649
item_3,105,61,12920402
item_4,324,178,46199102
item_5,313,163,43094955

Presently you have a dict each of posts , edits , and views which are each keyed to your "items", seems redundant.目前,您对每个postseditsviews都有一个字典,每个都与您的“项目”相关联,这似乎是多余的。

Alternatively, create a single dictionary keyed to your "items", and have the value of each item be a dictionary of posts , edits , views , like:或者,创建一个以您的“项目”为键的字典,并将每个项目的设为一个包含postseditsviews的字典,例如:

items = {}
items = {{'item_1': {'posts':1, 'edits':0, 'views':2345}
         {'item_2': {'posts':2, 'edits':8, 'views':330649}}

This way you can simply refer to items['item_2']['edits'] (which should yield 8 ) or items['item_1']['views'] (which should yield 2345 ), etc.通过这种方式,您可以简单地引用items['item_2']['edits'] (应该产生8 )或items['item_1']['views'] (应该产生2345 )等。

In your case, then something like:在你的情况下,然后是这样的:

# write the headers -- this could be refined
row = 0
worksheet.write(0, 1, 'posts')
worksheet.write(0, 2, 'edits')
worksheet.write(0, 3, 'views')

# write the data:
for itm in items:
    row += 1
    worksheet.write(row, 0, itm)
    for col, prop in enmumerate(items[itm]):
        worksheet.write(row, col+1, prop)
import pandas as pd

data = [{'posts': {'item_1': 1,
                   'item_2': 8,
                   'item_3': 105,
                   'item_4': 324,
                   'item_5': 313, }
         },
        {'edits': {'item_1': 1,
                   'item_2': 8,
                   'item_3': 61,
                   'item_4': 178,
                   'item_5': 163}
         },
        {'views': {'item_1': 2345,
                   'item_2': 330649,
                   'item_3': 12920402,
                   'item_4': 46199102,
                   'item_5': 43094955}
         }]

final_df = pd.DataFrame()

for id in range(0,len(data)):
    df = pd.DataFrame.from_dict(data[id])
    final_df = pd.concat([final_df, df], axis=1)

print (final_df)

final_df.to_excel('data.xlsx')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM