简体   繁体   中英

mapping a list of switches in python

I'm writing a mininet topology in python. There is a part in my code that is supposed to map the switches to the controllers. When I write the name of switches and controllers one by one, it's working fine:

cmap = {'s0': [c0], 's1': [c1], 's2': [c1]}

class MultiSwitch(OVSSwitch):
    "Custom Switch() subclass that connects to different controllers"
    def start(self, controllers):
        return OVSSwitch.start(self, cmap[self.name])

Now imagine I have 2 lists of switches:

switchL1 = [s1, s2, s3]
switchL2 = [s4, s5]

and I want to use a loop for this mapping instead of writing one by one, So that switches in first list will be connected to one controller and the ones in the second list will be mapped to another controller.

So it should be like this:

cmap = {'switchL1': [c0], 'switchL2': [c1]}

class MultiSwitch(OVSSwitch):
    "Custom Switch() subclass that connects to different controllers"
    def start(self, controllers):
        return OVSSwitch.start(self, cmap[self.name])

How can I do this? I tried this code:

cmap = {'%s': [c0] % (sw1) for sw1 in range(switches_L1), '%s': [c1] % (sw2) for sw2 in range(switches_L2)}

but I got invalid syntax error

Thats an invalid dictionary comprehension

cmap = {
    **{'%s': [c0] % (sw1) for sw1 in range(switches_L1)},
    **{'%s': [c1] % (sw2) for sw2 in range(switches_L2)}
}

If you want to create 2 linked dictionaries, create them separately, then unpack them using double asterisk ** notation into a new dictionary. The format is:

newdict = {**dict1, **dict2}

The problem was solved. We can use this:

switchL1 = ['s1', 's2', 's3']
switchL2 = ['s4', 's5']

cmap1={}
cmap2={}
for sw1 in switchL1:
    cmap1[sw1] = [c0]

for sw2 in switchL2:
    cmap2[sw2] = []

cmap={}
cmap.update(cmap1)
cmap.update(cmap2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM