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 list.
My goal is to end up with a data structure that looks like this:
router1 = {'Hostname': 'router1',
'OS-Type': 'ios',
'IP Address': '1.1.1.1',
'Username': 'user1',
'Password': 'cisco',}
router2 = {'Hostname': 'router2',
'OS-Type': 'ios',
'IP Address': '1.1.1.2',
'Username': 'user2',
'Password': 'cisco',}
sw1 = {'Hostname': 'sw1',
'OS-Type': 'cat-os',
'IP Address': '1.1.1.3',
'Username': 'user3',
'Password': 'cisco',}
These dictionaries would later be added to a LIST:
dictionary_list = [router1, router2, sw1]
Here's what my FOR LOOP currently looks like:
for i in range(len(device_list)):
dynamic_dictionary = {'Hostname': device_list[i][0],
'OS-Type': device_list[i][1],
'IP Address': device_list[i][2],
'Username': device_list[i][3],
'Password': device_list[i][4]}
Any help would be greatly appreciated.
Thanks!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With