Search code examples
pythondictionarytopology

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


It is for a dynamic ring topology project. Specifically, I need to name each node: s1,s2...sz, and name each host h1-1,h1-2,...hz-n. So z is the number of the nodes, and n is the number of the host connected to each node. So I have a list of the nodes, I am trying to use the node as a key to have another list of hosts, then I can put them in a dictionary for use. Just how can I achieve this goal? The example graph is as below:


Solution

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