[英]How to change the output of a dictionary format in to another
我的字典在下面
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"
}
]
}
]
}
我想要的輸出
keys_ipv4_address_1 192.168.1.1 physical_interface_2 0/1
這里keys_ipv4_address_1表示接口['device'] ['keyvalue'] ['id'= 1] ['ipv4-address']
physical_interface_2表示接口['device'] ['id'= 2] ['interface']
我的代碼如下
for k,v in d.items():
#print (v)
for i in v:
print (i['keyvalue'][0])
print (i['physical'][1])
但是我想要不同格式的輸出,如何實現。 像physical_interface_2
一樣,先進入physical
interface
然后進入ID 2
如何使用遞歸打印來指示要處理的部分,例如
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
然后調用recursive_print(d, "")
以打印路徑:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.