python将字符串转换为字典json
字符串输出具有以下值:python将字符串转换为字典json,python,Python,字符串输出具有以下值: interface Vlan364 ip policy route-map RM_OUT interface Vlan234 ip policy route-map RM_OUT interface Vlan235 ip policy route-map RM_OUT interface Ethernet1/2 ip policy route-map RM_IN interface Ethernet1/6 ip policy route-map RM_
interface Vlan364
ip policy route-map RM_OUT
interface Vlan234
ip policy route-map RM_OUT
interface Vlan235
ip policy route-map RM_OUT
interface Ethernet1/2
ip policy route-map RM_IN
interface Ethernet1/6
ip policy route-map RM_IN
1如何将其转换为disctionary,以便disctionary outputDict如下所示:
{
"interface":"Vlan364", "ip policy route-map":"RM_OUT",
"interface":"Vlan234", "ip policy route-map":"RM_OUT",
"interface":"Vlan235", "ip policy route-map":"RM_OUT",
"interface":"Ethernet1/2", "ip policy route-map":"RM_IN",
"interface":"Ethernet1/6", "ip policy route-map":"RM_IN",
}
这里的目标是识别与每个接口关联的ip策略路由图
2如何在上面的讨论中找到唯一的ip策略路由图并将其放入列表中。i、 e.上述讨论的结果将是:
route-map_list = [RM_OUT, RM_IN]
您可以使用正则表达式匹配关键字,然后使用user re.finditer搜索所有匹配项,并将匹配对象放入字典列表中
import re, json
output = """interface Vlan364
ip policy route-map RM_OUT
interface Vlan234
ip policy route-map RM_OUT
interface Vlan235
ip policy route-map RM_OUT
interface Ethernet1/2
ip policy route-map RM_IN
interface Ethernet1/6
ip policy route-map RM_IN"""
output_list = []
route_map_list = []
REGEX_STRING = r"interface ([A-Za-z0-9//]+)[\n\r ]+ip policy route-map ([A-Z_]+)"
for match in re.finditer(REGEX_STRING,output):
output_list.append(
{
"interface": match.group(1),
"ip policy route-map": match.group(2)
}
)
if match.group(2) not in route_map_list:
route_map_list.append(match.group(2))
print(json.dumps(output_list, indent=4))
print(route_map_list)
输出:
[
{
"interface": "Vlan364",
"ip policy route-map": "RM_OUT"
},
{
"interface": "Vlan234",
"ip policy route-map": "RM_OUT"
},
{
"interface": "Vlan235",
"ip policy route-map": "RM_OUT"
},
{
"interface": "Ethernet1/2",
"ip policy route-map": "RM_IN"
},
{
"interface": "Ethernet1/6",
"ip policy route-map": "RM_IN"
}
]
['RM_OUT', 'RM_IN']
你能给我们看看你已经试过的代码吗?您遇到了什么问题?Python字典键必须是唯一的,即“outputDict”中只能有一个“interface”和一个“ip policy route map”,有关更多信息,请参阅,因此您可能必须先更新所需的输出。