4

lldpctl -f keyvalue gives me output in this format:

lldp.eth0.via=LLDP
lldp.eth0.rid=1
lldp.eth0.age=286 days, 06:58:09
lldp.eth0.chassis.mac=<removed>
lldp.eth0.chassis.name=<removed>
lldp.eth0.chassis.descr=Not received
lldp.eth0.port.ifname=Gi1/19
lldp.eth0.port.descr=GigabitEthernet1/19
lldp.eth0.port.auto-negotiation.supported=yes
lldp.eth0.port.auto-negotiation.enabled=yes
lldp.eth0.port.auto-negotiation.10Base-T.hd=yes
lldp.eth0.port.auto-negotiation.10Base-T.fd=yes
lldp.eth0.port.auto-negotiation.100Base-X.hd=no
lldp.eth0.port.auto-negotiation.100Base-X.fd=yes
lldp.eth0.port.auto-negotiation.1000Base-T.hd=yes
lldp.eth0.port.auto-negotiation.1000Base-T.fd=yes
lldp.eth0.port.auto-negotiation.current=1000BaseTFD - Four-pair Category 5 UTP, full duplex mode
lldp.eth0.vlan.vlan-id=<removed>
lldp.eth0.vlan.pvid=yes
lldp.eth1.via=LLDP
lldp.eth1.rid=2
lldp.eth1.age=286 days, 06:58:08
lldp.eth1.chassis.mac=<removed>
lldp.eth1.chassis.name=<removed>
lldp.eth1.chassis.descr=Not received
lldp.eth1.port.ifname=Gi1/19
lldp.eth1.port.descr=GigabitEthernet1/19
lldp.eth1.

I want to use Python to parse the output into a dictionary like this:

lldp['eth1']['port']['descr'] = 'GigabitEthernet1/19'

With this consideration too:

lldp['eth0']['rid'] = '1'

Is there a reliable way to do this with python where I have an unpredictable depth to parse through?

1

1 Answer 1

4

Assuming you have the output in a multiline string named output:

output_dict = {}
lldp_entries = output.split("\n")

for entry in lldp_entries:
    path, value = entry.strip().split("=", 1)
    path = path.split(".")
    path_components, final = path[:-1], path[-1]

    current_dict = output_dict
    for path_component in path_components:
        current_dict[path_component] = current_dict.get(path_component, {})
        current_dict = current_dict[path_component]
    current_dict[final] = value
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.