簡體   English   中英

Python 嵌套字典列表到 CSV 文件

[英]Python list of nested dictionaries to CSV File

我有一個字典列表,上面有其他字典。
字典:

[[{'id': 1, 'networkId': 'L_1111', 'name': 'VLAN1', 'applianceIp': '1.1.1.1', 'subnet': '1.1.1.0/24', 'fixedIpAssignments': {}, 'reservedIpRanges': [], 'dnsNameservers': 'upstream_dns', 'dhcpHandling': 'Run a DHCP server', 'dhcpLeaseTime': '1 day', 'dhcpBootOptionsEnabled': False, 'dhcpOptions': [], 'interfaceId': '1', 'networkName': 'NETWORK1'}, {'id': 2, 'networkId': 'L_2222', 'name': 'VLAN2', 'applianceIp': '2.2.2.2', 'subnet': '2.2.2.0/24', 'fixedIpAssignments': {}, 'reservedIpRanges': [], 'dnsNameservers': 'upstream_dns', 'dhcpHandling': 'Do not respond to DHCP requests', 'interfaceId': '2', 'networkName': 'NETWORK2'}]]

JSON版本:

[
   [
      {
         "id": 1,
         "networkId": "L_1111",
         "name": "VLAN1",
         "applianceIp": "1.1.1.1",
         "subnet": "1.1.1.0/24",
         "fixedIpAssignments": {},
         "reservedIpRanges": [],
         "dnsNameservers": "upstream_dns",
         "dhcpHandling": "Run a DHCP server",
         "dhcpLeaseTime": "1 day",
         "dhcpBootOptionsEnabled": false,
         "dhcpOptions": [],
         "interfaceId": "1",
         "networkName": "NETWORK1"
      },
      {
         "id": 2,
         "networkId": "L_2222",
         "name": "VLAN2",
         "applianceIp": "2.2.2.2",
         "subnet": "2.2.2.0/24",
         "fixedIpAssignments": {},
         "reservedIpRanges": [],
         "dnsNameservers": "upstream_dns",
         "dhcpHandling": "Do not respond to DHCP requests",
         "interfaceId": "2",
         "networkName": "NETWORK2"
      },
   ]
]

我正在嘗試將其移至 CSV 文件。 但是,我還沒有弄清楚該怎么做。 我嘗試使用 pandas 庫,但它沒有給我我正在尋找的輸出。
像這樣的東西:

id,networkId,name,applianceIp,subnet,fixedIpAssignments,reservedIpRanges,dnsNameservers,dhcpHandling,interfaceId,networkName
1,L_1111,VLAN1,1.1.1.1,1.1.1.0/24,{},[],upstream_dns,Do not respond to DHCP requests,1,NETWORK1
2,L_2222,VLAN2,2.2.2.2,2.2.2.0/24,{},[],upstream_dns,Do not respond to DHCP requests,2,NETWORK2

預期輸出:

id networkId name     applianceIP subnet 
1  L_1111    VLAN1    1.1.1.1     1.1.1.0/24
2  L_2222    VLAN2    2.2.2.2     2.2.2.0/24

我會考慮使用 pandas 將列表轉換為數據框,然后您就可以將其導出到 csv 文件。

import pandas as pd

data = [[{'id': 1, 'networkId': 'L_1111', 'name': '1', 'applianceIp': '1.1.1.1', 'subnet': '1.1.1.0/24', 'fixedIpAssignments': {}, 'reservedIpRanges': [], 'dnsNameservers': 'upstream_dns', 'dhcpHandling': 'Run a DHCP server', 'dhcpLeaseTime': '1 day', 'dhcpBootOptionsEnabled': False, 'dhcpOptions': [], 'interfaceId': '1', 'networkName': '1'}, {'id': 2, 'networkId': 'L_2222', 'name': '2', 'applianceIp': '2.2.2.2', 'subnet': '2.2.2.0/24', 'fixedIpAssignments': {}, 'reservedIpRanges': [], 'dnsNameservers': 'upstream_dns', 'dhcpHandling': 'Do not respond to DHCP requests', 'interfaceId': '2', 'networkName': '2'}]]

df = pd.DataFrame(data[0])
df.to_csv("output.csv")

我使用了 csv 模塊。

import json
import csv
import os

PATH = os.path.dirname(__file__)    # Get the path of the used directory

with open(PATH+r"\input.json", "r") as file:    # Access the data    
    json_data = json.load(file)
    json_data = [item for item in json_data[0]]

with open(PATH+r"\output.csv", "w+", newline='') as file:
    writer = csv.writer(file)
    headers = [list(data.keys()) for data in json_data]     # Divide the data in
    rows = [list(data.values()) for data in json_data]    # headers and rows
    for i in range(len(json_data)):
        writer.writerow(headers[i])    # Write everything
        writer.writerow(rows[i])

如果您不想有標題,只需刪除此行writer.writerow(headers[i])

這是我作為輸出得到的數據:

id,networkId,name,applianceIp,subnet,fixedIpAssignments,reservedIpRanges,dnsNameservers,dhcpHandling,dhcpLeaseTime,dhcpBootOptionsEnabled,dhcpOptions,interfaceId,networkName
1,L_1111,VLAN1,1.1.1.1,1.1.1.0/24,{},[],upstream_dns,Run a DHCP server,1 day,False,[],1,NETWORK1
id,networkId,name,applianceIp,subnet,fixedIpAssignments,reservedIpRanges,dnsNameservers,dhcpHandling,interfaceId,networkName
2,L_2222,VLAN2,2.2.2.2,2.2.2.0/24,{},[],upstream_dns,Do not respond to DHCP requests,2,NETWORK2

如果您使用 pandas 數據框,您可以輕松編寫 csv 文件。 將 DataFrame 的每一列保存到 csv 文件中的單獨列。

df.to_csv(r'myData.csv',sep=';',encoding="utf-8")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM