My Dictionary is below
d = {
"interface": [
{
"device": "device1",
"keyvalue": [
{
"id": 1,
"ipv4-address": "192.168.1.1",
},
{
"id": 2,
"ipv4-address": "192.168.1.2",
}
],
"physical": [
{
"id": "1",
"interface": "0/0"
},
{
"id": "2",
"interface": "0/1"
}
]
}
]
}
My desired output
keys_ipv4_address_1 192.168.1.1 physical_interface_2 0/1
Here keys_ipv4_address_1 means interface['device']['keyvalue']['id' = 1]['ipv4-address']
physical_interface_2 means interface['device']['id' = 2]['interface']
My Code is below
for k,v in d.items():
#print (v)
for i in v:
print (i['keyvalue'][0])
print (i['physical'][1])
But I want the output in different format, how to achieve that. like physical_interface_2
means go to physical
then interface
then id 2
how about use recursive print to indicate which part is handling, such as
def recursive_print(a, output):
if type(a) == str:
print(output, a)
return
if type(a) == int:
print(output, a)
return
if type(a) == list:
for i in a:
recursive_print(i, output)
return
if type(a) == dict:
for key in a:
recursive_print(a[key], output + ('_' if output else '') + key)
return
Then call recursive_print(d, "")
to print the path:
interface_device device1
interface_keyvalue_id 1
interface_keyvalue_ipv4-address 192.168.1.1
interface_keyvalue_id 2
interface_keyvalue_ipv4-address 192.168.1.2
interface_physical_id 1
interface_physical_interface 0/0
interface_physical_id 2
interface_physical_interface 0/1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.