我有一个元组列表:
x = [('router_1', '0/47', '0/17', 'router_2'),
('router_1', '0/48', '0/17', 'router_3'),
('router_4', '0/47', '0/18', 'router_5'),
('router_4', '0/48', '0/18', 'router_6')]
目标是构建如下数据:
dict = {"details": [
{
"router_1": {
"connections": [
{
"side_a": {
"device": "router_1",
"interface": "0/47",
},
"side_b": {
"interface": "0/17",
"device": "router_2",
}
},
{
"side_a": {
"device": "router_1",
"interface": "0/48",
},
"side_b": {
"interface": "0/17",
"device": "router_3",
}
}
]
}
},
{
"router_4": {
"connections": [
{
"side_a": {
"device": "router_4",
"interface": "0/47",
},
"side_b": {
"interface": "0/17",
"device": "router_5",
}
},
{
"side_a": {
"device": "router_4",
"interface": "0/48",
},
"side_b": {
"interface": "0/17",
"device": "router_6",
}
}
]
}
}
]
}
请注意:
import collections
data_dict = collections.defaultdict(list)
result = {}
for item in x:
router_a, router_a_int, router_b_int, router_b = item
result[side_a] = data_dict["connections"].append({"side_a": {
"hostname": router_a,
"interface": router_a_int},
"side_b": {
"interface": router_b_int,
"hostname": router_b
}})
但是,字典的值显示为“None”。看起来每次追加都会导致值为 None 但我虽然使用 collections.defaultdict(list) 应该消除这个问题
请您帮忙。
谢谢你
您只需要调整在循环内创建字典结构的方式。
试试这个:
from collections import defaultdict
data_dict = defaultdict(list)
for item in x:
router_a, router_a_int, router_b_int, router_b = item
data_dict[router_a].append({
"side_a": {
"device": router_a,
"interface": router_a_int
},
"side_b": {
"interface": router_b_int,
"device": router_b
}
})
result = {"details": [{"{}".format(router): {"connections": connections}} for router, connections in data_dict.items()]}
print(result)