簡體   English   中英

從另一個字典列表創建字典列表

[英]Creating a list of dictionaries from another list of dictionaries

對不起,很長的帖子。 幾天來,我一直試圖弄清楚這一點。 但是,我難住了。 Python 不是我的母語。

我正在從 API 中提取包含有關 1,400 台主機信息的字典列表。

我將 json 數據轉換為 python 字典列表。 我創建了第二個列表,用於填充新的字典列表,其中包含從 API 中提取的列表中的信息子集。

我創建了一個我需要從中獲取信息的鍵的列表。 接下來,我創建了兩個 for 循環。 第一個遍歷字典的原始列表,第二個遍歷我想要放入新字典列表的鍵列表。

如果我在兩個循環中添加打印語句,我可以確認我正在遍歷我正在尋找的正確信息,並且此信息正在添加到新的字典列表中。

字典列表、鍵列表和新字典(將在循環中使用)都在 scope 中定義為全局。

但是,稍后在腳本中,當我 go 引用最終字典列表的任何特定元素時,所有 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 object 的引用,您在每個循環中都對其進行了修改。 嘗試類似:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM