创建动态字典名称

问题描述 投票:0回答:2

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

任何帮助将不胜感激。

谢谢!

python-3.x dictionary
2个回答
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)

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

希望这能回答你的问题。

© www.soinside.com 2019 - 2024. All rights reserved.