python的嵌套词典列表到CSV文件

发布于 2025-02-09 09:50:55 字数 2222 浏览 1 评论 0原文

我有一个词典清单,上面有其他字典。
字典:

[[{'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 Library,但这并没有给我我想要的输出。
这样的东西:

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

I have a list of dictionaries that have other dictionaries on them.
Dictionary:

[[{'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 version:

[
   [
      {
         "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"
      },
   ]
]

I am trying to move this to a CSV file. However, I haven't figured out how to do it. I tried with pandas library but it isn't giving me the output that I am looking for.
Something like this:

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

Expected Output:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

A君 2025-02-16 09:50:55

我会考虑使用熊猫将列表转换为数据框架,然后您将能够将其导出到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")

I'd look at using pandas to convert the list to a dataframe and then you'll be able to export that to a csv file.

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")
天赋异禀 2025-02-16 09:50:55

我使用了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

I used the csv module.

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])

If you don't want to have headers just remove this line writer.writerow(headers[i])

Here is the data I get as output:

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
痴梦一场 2025-02-16 09:50:55

如果使用PANDAS DataFrame,则可以轻松编写CSV文件。将数据框的每列保存到CSV文件中的分离列。

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

If you use pandas dataframe, you can easily write csv file. Save each column of DataFrame to seperated column in csv file.

df.to_csv(r'myData.csv',sep=';',encoding="utf-8")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文