如何在Python中命名嵌套字典的每个实例?

时间:2016-07-06 15:50:49

标签: python json dictionary

我编写此代码来创建嵌套字典,但我无法命名每个实例。

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))

我可以获得一些帮助来获取嵌套字典中每个字典实例的名称吗?

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"
 }
}
>>>