python中的迭代dictonaries

时间:2017-02-28 04:47:38

标签: python

我在其中一个编码挑战中遇到过这个问题,虽然我由于时间限制而无法解决它并且是python的新手。我现在尝试解决它。但我想知道是否有更简单有效的方法来解决这个问题。

问题

config_file=[ \
    "[__Box1A,Box1B__]", \
    "portA:enabled=true", \
    "portB:vlan=10", \
    "portC:vlan=200", \
    "[__Box2__]", \
    "portA:poe=false", \
    "portB:speed=100mbps",\
    "[__Box3__]", \
    "portA:use_lld=false", \
    ]

port_mappings=[ \
    "[__Box1A,Box1B__]", \
    "portA:Eth1/1", \
    "portB:Eth1/2", \
    "portC:Eth1/3", \
    "[__Box3__]", \
    "portA:Eth3/1", \
    "[__Box2__]", \
    "portA:Eth2/1", \
    "portB:Eth2/2",\
    ]

将2 List作为config_file和port_mappings,结果数组应如下所示。

result_file=[ \
    "[__Box1A,Box1B__]", \
    "Eth1/1:enabled=true", \
    "Eth1/2:vlan=10", \
    "Eth1/3:vlan=200", \
    "[__Box2__]", \
    "Eth2/1:poe=false", \
    "Eth2/2:speed=100mbps",\
    "[__Box3__]", \
    "Eth3/1:use_lld=false", \
    ]

我的解决方案

A1dict2={}
for item in config_file:
    if item.startswith('[_'):
        key1=item
        dict1={}
        A1dict2[key1]=dict1
    else:
        sitem=re.split(':',item)
        dict1[sitem[0]]=sitem[1]
print A1dict2

A2dict2={}
for item in port_mappings:
    if item.startswith('[_'):
        key1=item
        dict1={}
        A2dict2[key1]=dict1
    else:
        sitem=re.split(':',item)
        dict1[sitem[0]]=sitem[1]
print A2dict2

A3dict2={}

dict3 = {}        
for key in A1dict2:
        tmpdict = {}
        for key_child, item in A1dict2[key].iteritems():
            tmpdict[A2dict2[key][key_child]] = item
        dict3[key] = tmpdict

newlist=[]
for key,value in dict3.iteritems():
    newlist.append(key)
    for j in dict3[key].items():
        x=map(str,j)
        newlist.append(":".join(x))
print newlist

1 个答案:

答案 0 :(得分:1)

+1对Code Review的建议,你的方式看起来很好,这里有几行:

from collections import OrderedDict
config_dict = OrderedDict()
port_map_dict = OrderedDict()

def map_items(list_of_items, ordered_dict):
    for i in list_of_items:
        if i.startswith('[__Box'):
            current = i
            ordered_dict[i] = OrderedDict()
        else:
            port, option = i.split(':')
            ordered_dict[current][port] = option

map_items(config_file, config_dict)
map_items(port_mappings, port_map_dict)

result_file = []
for box, items in config_dict.iteritems():
    result_file.append(box)
    for port, value in items.iteritems():
        result_file.append('{}:{}'.format(port_map_dict[box][port], value))

结果:

In [47]: result_file
Out[47]:
['[__Box1A,Box1B__]',
 'Eth1/1:enabled=true',
 'Eth1/2:vlan=10',
 'Eth1/3:vlan=200',
 '[__Box2__]',
 'Eth2/1:poe=false',
 'Eth2/2:speed=100mbps',
 '[__Box3__]',
 'Eth3/1:use_lld=false']