创建动态字典名称

时间:2019-04-20 23:46:59

标签: python-3.x dictionary

Python的新手。我正在尝试使用从另一个列表内LIST的第一个元素派生的字典名称在FOR LOOP内部动态创建新字典。

我的目标是最终得到一个看起来像这样的数据结构:

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',}

这些词典稍后会添加到列表中:

dictionary_list = [router1, router2, sw1]

这是我的FOR LOOP当前的样子:

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]}

任何帮助将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:0)

对于您的for循环,

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

我们做了什么,而不是使用在数组中使用索引的旧样式,而是将其替换为迭代器。有多种方法可以迭代Python中不同类型的数据。在这里阅读它们:loops in python

希望这能回答您的问题。

答案 1 :(得分:0)

为什么不立即将要创建的字典追加到列表中。另外,请事先定义键列表,以便在迭代键列表时可以追加字典

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)
相关问题