简体   繁体   English

Python:如何将嵌套字典(字典中列表中的字典)写入 excel xlsx 文件

[英]Python: How to write a nested dictionary (dictionaries in lists in dictionaries) to a excel xlsx file

I am very new to Python and and i am looking for some guidance on how to create a *xlsx file from the following nested dictionary.我对 Python 非常陌生,我正在寻找有关如何从以下嵌套字典创建 *xlsx 文件的指导。 I am aware that i have to use a package like openpyxl to generate the *xlsx File and that i have to use some nested for loops or a dictionary comprehension to get the Data.我知道我必须使用像 openpyxl 这样的包来生成 *xlsx 文件,并且我必须使用一些嵌套的 for 循环或字典理解来获取数据。 But i am not able to put all things together.但我无法将所有东西放在一起。 Any Help/Tip is very welcome.非常欢迎任何帮助/提示。

snapshot = {
  "SHAMk98bspucm02.some-domain.invalid": [
    {
      "Name": "SEP1CDEA7837E70",
      "Device Class": "Phone",
      "Model": 683,
      "Description": "+4912345556661 - BFE Alexandra Balzer",
      "Directory Number": "+4912345556661",
      "Registered On": "SHAMk98bspucm02.some-domain.invalid",
      "IP Address": "192.29.53.112",
      "Status": "Registered"
    },
    {
      "Name": "SEP1CDEA7837E12",
      "Device Class": "Phone",
      "Model": 683,
      "Description": "+4912345556662 - Michael H\u00f6nemann",
      "Directory Number": "+4912345556662",
      "Registered On": "SHAMk98bspucm02.some-domain.invalid",
      "IP Address": "192.29.41.111",
      "Status": "Registered"
    }
  ],
  "shamk98bspucm01.some-domain.invalid": [
    {
      "Name": "CSFOSTERAUC",
      "Device Class": "Phone",
      "Model": 503,
      "Description": "+4912345556663 - Christian Osterauer",
      "Directory Number": "+4912345556663",
      "Registered On": "shamk98bspucm01.some-domain.invalid",
      "IP Address": "192.28.11.13",
      "Status": "Registered"
    },
    {
      "Name": "CSFTHURNERF",
      "Device Class": "Phone",
      "Model": 503,
      "Description": "+4912345556665 - Florian Thurner",
      "Directory Number": "+4912345556665",
      "Registered On": "shamk98bspucm01.some-domain.invalid",
      "IP Address": "192.28.171.12",
      "Status": "Registered"
    }
  ],
  "skolrzucm03.some-domain.invalid": [
    {
      "Name": "CSFWIESBOMI",
      "Device Class": "Phone",
      "Model": 503,
      "Description": "+4912345556665 - Wiesboeck Michael",
      "Directory Number": "+4912345556665",
      "Registered On": "skolrzucm03.some-domain.invalid",
      "IP Address": "192.28.11.81",
      "Status": "Registered"
    },
    {
      "Name": "SEP6C6CD3A5C94E",
      "Device Class": "Phone",
      "Model": 684,
      "Description": "+4912345556666 - Nina Schraud",
      "Directory Number": "+4912345556666",
      "Registered On": "skolrzucm03.some-domain.invalid",
      "IP Address": "192.28.11.84",
      "Status": "Registered"
    }
  ]
}

The *xlsx File should look like the following: *xlsx 文件应如下所示:

|Name|Device Class|Model|Description|Directory Number|Registered On| IP Address| Status|
|SEP1CDEA7837E70|Phone|683|+4912345556661 - BFE Alexandra Balzer|+4912345556661|SHAMk98bspucm02.some-domain.invalid|192.29.53.112|Registered|

I tried the following code to get to the values of the inner dictionary.我尝试了以下代码来获取内部字典的值。

for cm_nodes,device_info in snapshot.items():
    # print (cm_nodes,device_info) # Gets me keys and the values of the Outer Dict. Value is of type list
    for device_info_list in device_info:
        # print (device_info_list)
         for device_key,device_value in device_info_list.items(): # Gets me all the Dict Values of the inner Dictionaries
                print(device_value)

But now i am stuck.但现在我被困住了。 Questions i have: - how to determine where a "device" starts ('name Key') and where it stops ('Status')我的问题: - 如何确定“设备”的开始位置(“名称键”)和停止位置(“状态”)

For the .xlsx generation I would use XlsxWriter and Pandas dataframe.对于 .xlsx 一代,我将使用 XlsxWriter 和 Pandas 数据框。 I assume you have this data in a variable named dictionary .我假设您在名为dictionary的变量中有这些数据。

import pandas as pd

# Get the "outer" dictionary keys
outer_dict_keys = dictinary.keys()
# Define the Pandas dataframe
df = pd.DataFrame(columns=dictinary["SHAMk98bspucm02.some-domain.invalid"]    [0].keys())       # It is quite ugly :D, just lack of time ... change it!

# Iterate through "outer" dictionary
for outer_dict_key in outer_dict_keys:
    # With this you get: SHAMk98bspucm02.some-domain.invalid, ...
    interior_dict = dictinary[outer_dict_key][0]        # The [0] is there     because it is in a list
    # Get the "interior" dictionary keys
    interior_dict_keys = interior_dict.keys()

    # This variable contains the data for one row.
    row = dict()
    for interior_dict_key in interior_dict_keys:
        # With this you get: Name, Device Class, Model ..
        row[interior_dict_key] = interior_dict[interior_dict_key]

    # You can reach the values like this:
    df = df.append(row, ignore_index=True)

# Create an xlsxwriter object and save the created Excel file
writer = pd.ExcelWriter('filename.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='sheet_name', index=False)
writer.save()
writer.close()

I hope it will help you :)我希望它会帮助你:)

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

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