2016-07-06 84 views
-5

我寫了這段代碼來創建一個嵌套字典,但我無法命名每個實例。如何命名Python中嵌套字典的每個實例?

def genvlandict(num,attrs): 
    val=num 
    vlans = [] 
    for i in range(val): 
     vlans.append(dict([("Vlan_Attr"+str(i)+'.'+str(x), "val"+str(i)+'.'+str(x)) for x in range(0, attrs, +1)])) 
    return vlans 

print(json.dumps(genvlandict(5,3), indent=1)) 

我可以得到一些幫助,以獲得嵌套字典中的每個字典實例的名稱?

+0

我不明白的問題。這些字典在列表中。他們爲什麼需要名字? –

回答

0

vlans更改爲字典?對於一些最小的變化,您的代碼將是這樣的:

import json 

def genvlandict(num,attrs): 
    val=num 
    vlans = {} 
    for i in range(val): 
     vlans['dict%d' % i] = dict([("Vlan_Attr"+str(i)+'.'+str(x), "val"+str(i)+'.'+str(x)) for x in range(0, attrs, +1)]) 
    return vlans 

print(json.dumps(genvlandict(5,3), indent=1)) 

,導致:

>>> 
{ 
"dict4": { 
    "Vlan_Attr4.2": "val4.2", 
    "Vlan_Attr4.1": "val4.1", 
    "Vlan_Attr4.0": "val4.0" 
}, 
"dict1": { 
    "Vlan_Attr1.2": "val1.2", 
    "Vlan_Attr1.0": "val1.0", 
    "Vlan_Attr1.1": "val1.1" 
}, 
"dict0": { 
    "Vlan_Attr0.2": "val0.2", 
    "Vlan_Attr0.1": "val0.1", 
    "Vlan_Attr0.0": "val0.0" 
}, 
"dict3": { 
    "Vlan_Attr3.0": "val3.0", 
    "Vlan_Attr3.1": "val3.1", 
    "Vlan_Attr3.2": "val3.2" 
}, 
"dict2": { 
    "Vlan_Attr2.1": "val2.1", 
    "Vlan_Attr2.0": "val2.0", 
    "Vlan_Attr2.2": "val2.2" 
} 
} 
>>>