Skip to content Skip to sidebar Skip to footer

Creating A Dynamic Dictionary Name

Very new to Python. I'm trying to dynamically create new dictionaries inside of a FOR LOOP with dictionary names that are derived from the first element of a LIST inside another li

Solution 1:

Why not append the dictionaries you are creating to a list right away. In addition, define the list of keys before hand, so that you can append the dictionary while iterating over the list of keys

li = []
keys = ['Hostname', 'OS-Type', 'IP Address', 'Username', 'Password']
for i in range(len(device_list)):
    dct = {}
    for idx, key in enumerate(keys):
        dct[key] =  device_list[i][idx]
    li.append(dct)

Solution 2:

For your for loop,

# Python3 code to iterate over a list 
dict_list = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] 
host_list = []
# Using for loop 
for i in list:
    host_dict = {'Hostname': i[0], 'OS-Type': i[1], 'IP Address': i[2], 'Username': i[3], 'Password': i[4]}
    host_list.append(host_dict)

What did we do, in place of using the older style of using the index in the array we replaced it with an iterator. There are multiple ways to iterate over different types of data in Python. Read up on them here: loops in python

Hope this answers your question.

Post a Comment for "Creating A Dynamic Dictionary Name"