[Solved] How to loop a list and append it to a dictionary in a loop?


I think you are looking for something along the lines of this:

# run with python dynamictopo.py z n
# e.g.: python dynamictopo.py 3 2
import sys

z = int(sys.argv[1])  # number of nodes
n = int(sys.argv[2])  # number of hosts

nodes = []
for i in range(0, z):
    nodes.append("s" + str(i + 1))

print(nodes)

dct = {}
for j, node in enumerate(nodes):
    hosts = []
    for h in range(0, n):
        hosts.append("h" + nodes[j][1] + "-" + str(h + 1))
    dct[node] = hosts

print(dct)

This will print [‘s1’, ‘s2’, ‘s3’] and {‘s2’: [‘h2-1’, ‘h2-2’], ‘s3’: [‘h3-1’, ‘h3-2’], ‘s1’: [‘h1-1’, ‘h1-2’]} if you use 3 and 2 as command line arguments. Note that dictionaries are unordered.

Or use this:

# run with python dynamictopo.py z n
# e.g.: python dynamictopo.py 3 2
import sys

z = int(sys.argv[1])  # number of nodes
n = int(sys.argv[2])  # number of hosts

dct = {}
for i in range(z):
    hosts = []
    for h in range(0, n):
        hosts.append("h" + str(i + 1) + "-" + str(h + 1))
    dct["s" + str(i + 1)] = hosts

print(dct)

4

solved How to loop a list and append it to a dictionary in a loop?