Skip to main content
 首页 » 编程设计

python之从另一个词典列表创建一个词典列表

2024年11月01日11lhb25

抱歉发了这么长的帖子。几天来我一直在努力解决这个问题。但是,我很难过。 Python 不是我的母语。

我正在从 API 中提取包含有关 1,400 台主机的信息的字典列表。

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

我创建了一个 key 列表,我需要从中获取信息。接下来,我创建两个 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 新手。

请您参考如下方法:

您列表中的所有条目似乎都是对 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]