根据其他词典列表创建词典列表

时间:2019-10-09 15:18:06

标签: python

很抱歉,很长的帖子。我已经尝试了好几天了。但是,我很困惑。 Python不是我的母语。

我正在从API提取包含有关1400台主机的信息的词典列表。

我将json数据转换为字典的python列表。我创建了第二个列表,用于填充新列表 字典列表,其中包含从API中提取的列表信息的子集。

我创建需要信息的键的列表。接下来,我创建两个for循环。第一个遍历 字典的原始列表,第二个遍历我要放入的键列表 新的词典列表。

如果在两个循环中添加打印语句,则可以确认我在遍历正确的信息 我正在寻找并且此信息已添加到新的词典列表中。

都定义了字典列表,键列表和新字典(将在循环中使用) 在全球范围内。

但是,在脚本的后面,当我去引用字典最终列表中的任何特定元素时, 所有1,400个字典的值与原始字典列表的最后一项相同。

host_info是从API提取的词典列表

host_fields是我想从host_info解析的键的列表

# New list of dictionaries. We will populate the keys in these
# from the host_fields list above.
export_list_of_dictionaries = []

# New dictionary for use in populating in export_list_of_dictionaries
new_host = {}

# Loop through the host_info list of dictionaries to pull
# the specific host_fields
for index in  range(len(host_info)):
    for field in host_fields:
        # Add the field as a key to the new_host dictionary
        new_host[field] = host_info[index][field]

    # **** The line above is cycling through the fields of host_fields correctly ****

# print(index) **** the index is cycling through host_info correctly ****
# Add the new_host dictionary to the new export_list_of_dictionaries
export_list_of_dictionaries.append(new_host)

# **** The print statement below shows that each of the elements has the correct ip
#print(export_list_of_dictionaries[index]['ip'])
# print(len(export_list_of_dictionaries)) **** This printed the correct number of elements ****

原始字典列表中的键可以正确打印。 host_info中的每个IP不同。

# Print the IP for the first element in each list of dictionary
print("IP from the first element of the original list of dictionaries")
print(host_info[0]['ip'])
print(host_info[1]['ip'])
print(host_info[-1]['ip'])

问题在这里变得显而易见: 但是,最终字典列表中的键都具有相同的IP,这是不正确的。

print("IP from the first element of the final list of dictionaries")
print(export_list_of_dictionaries[0]['ip'])
print(export_list_of_dictionaries[1]['ip'])
print(export_list_of_dictionaries[-1]['ip'])

请只提供简单的答案,我是Python的新手。

1 个答案:

答案 0 :(得分:1)

似乎列表中的所有条目都是对new_host对象的引用,您需要在每个循环中对其进行修改。尝试类似的东西:

for index in  range(len(host_info)):
    # Add a new blank dict to the list
    export_list_of_dictionaries.append({})
    for field in host_fields:
        # Add the field as a key to the new element of the list
        export_list_of_dictionaries[index][field] = host_info[index][field]