从CSV创建字典,但不要重复顶级。

3

我正在尝试使用脚本创建一个API。它可以运行,但是我需要让它迭代CSV文件,而不是将port_config附加到每一行:

读取这个CSV文件:

device_id,port,description
4444,eth1/1,test1
1111,eth1/2,test2
2222,eth1/3,test3
1234,eth1/4,test4

我目前所拥有的代码如下:
for device_id,port,description in devices:
    print(device_id,port,description)
    payload="{\n \"port_config\": { \"%s\": { \"description\": \"%s\"                      
             }\n}\n}" % (port,description)
    print(payload)

上述结果为:

{
 "port_config": { "interfacex/x": { "description": "test1" }
}
}
{
 "port_config": { "interfacex/x": { "description": "test2" }
}
}
{
 "port_config": { "interfacex/x": { "description": "test3" }
}
}
{
 "port_config": { "interfacex/x": { "description": "test4" }
}
}

期望的结果:

{
    "port_config": {
        "eth1/1": {"description": "test0,"},
        "eth1/2": {"description": "test1,"},
        "eth1/3": {"description": "test2,"},
        "eth1/4": {"description": "test3,"}
    }
}

问题提得好多了,感谢您付出努力将其整理好。 - David Buck
感谢您的帮助。我是新手,还有很多东西要学习。下次我会尽力在第一次尝试中做得更好。 - Ali
2个回答

2

您的问题仍有一个问题。CSV示例与所需输出不完全匹配。假设您有以下CSV字符串。

devices = """device_id,port,description
4444,eth1/1,test1
1111,eth1/2,test2
2222,eth1/3,test3
1234,eth1/4,test4
"""

您希望获得以下输出:

d = {
    "port_config": {
        "eth1/1": {"description": "test1,"},
        "eth1/2": {"description": "test2,"},
        "eth1/3": {"description": "test3,"},
        "eth1/4": {"description": "test4,"},
    }
}

你可以通过进行以下一些字典操作来轻松实现这一点,具体如下:
import csv
from pprint import pprint

# Input csv.
devices = """device_id,port,description
4444,eth1/1,test1
1111,eth1/2,test2
2222,eth1/3,test3
1234,eth1/4,test4
"""

# Read the data using Python's built-in csv module.
lines = devices.splitlines()
reader = csv.reader(lines)
devices = list(reader)

# Let's initialize the target payloads data structure.
payload = {
    "port_config": {},
}

for idx, (device_id, port, description) in enumerate(devices):
    if idx == 0:
        continue # This line skips the header.
    payload["port_config"][port] = {"description": description}

pprint(payload)

这将会给你以下输出结果:
{'port_config': {'eth1/1': {'description': 'test1'},
                 'eth1/2': {'description': 'test2'},
                 'eth1/3': {'description': 'test3'},
                 'eth1/4': {'description': 'test4'}}}

所以我之前使用了“device_id”部分来做其他事情,这就是为什么它不在期望的结果中。我无法完全理解“lines = devices.splitlines()”这一部分,但我使用“open”读取了文件,然后其余部分相同。现在我已经得到了期望的结果,只需要让PUT起作用。我认为问题可能是因为我得到的是单引号而不是双引号,这可能导致了问题。 - Ali

0
你也可以通过 pandas 实现这个功能 -
import pandas as pd
df = pd.read_csv('inp_file.csv')
result = {'port_config' : {item['port'] :{"description": item['description']} for item in df[['port','description']].to_dict(orient='records')}}

1
谢谢,我也会尝试一下,看看效果如何。更新后会发布的。 - Ali
@Ali 当然,没问题 :) - Nk03

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接