user2009169 user2009169 - 1 month ago 6
Python Question

Python create an array from dictionary

I'm not sure if this is the correct title for what I want to do but, I have a list at the same level and want to use "vlan" as the top level and the "name" as an attribute. Below is the list.

vlans = ['vlan 1', 'name default', 'vlan 2', 'name non-default']


Code to create a dictionary. Not sure if I need to do this.

for v in vlans:
type = v.split(" ")
value = dict([(type[0], type[1])])
print(value)


Output

{'vlan': '1'}
{'name': 'default'}
{'vlan': '2'}
{'name': 'non-default'}


The reply marked as answer will work in this situation. Could this output also be achieved?

{
"vlan 1":{
"name": "default"
},
"vlan 2":{
"name": "non-default"
}
}

Answer

Not sure about what you're looking for, so here's a guess :

vlans = ['vlan 1', 'name default', 'vlan 2', 'name non-default']
output = {}

for i in range(len(vlans)/2):
    output[vlans[2*i]] = vlans[2*i + 1]

This produces {'vlan 1': 'name default', 'vlan 2': 'name non-default'} Is it what you meant by :

use "vlan" as the top level and the "name" as an attribute

EDIT : As an afterthought, maybe you wanted to get rid of "vlan" and "name" everywhere. Here is a way to do this.

vlans = ['vlan 1', 'name default', 'vlan 2', 'name non-default']
output = {}

for i in range(len(vlans)/2):
    vlan_number = (vlans[2*i].split())[1]
    name = (vlans[2*i + 1].split())[1]
    output[vlan_number] = name

This produces the output :

{'1': 'default', '2': 'non-default'}

Please note that here the vlan numbers are strings. To have them as integers, just convert them in the last line for instance :

output[int(vlan_number)] = name
Comments