[英]Replace values of dictionaries (in a list) with a value in list of lists
以下是我正在使用的字典列表(我故意保留了 2 個):
ld= [{'this': 1, 'is': 1, 'the': 1, 'first': 1, 'document': 1}, {'this': 1, 'document': 2, 'is': 1, 'the': 1, 'second': 1}]
以下是我的清單(我故意保留了 2 個):
b=[[0.2, 0.2, 0.2, 0.2, 0.2], [0.16666666666666666, 0.3333333333333333, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666]]
dict 鍵的計數為 10,b 中值的計數也是 10。我想用列表 ld 中具有相同索引值的 dict.values() 替換 b 中的值(即第一個 dict 中的“this”鍵應該獲取 b) 中的第一個值。 我怎樣才能完成這個任務?
這是一個快速,不優雅的解決方案:
ld= [{'this': 1, 'is': 1, 'the': 1, 'first': 1, 'document': 1}, {'this': 1, 'document': 2, 'is': 1, 'the': 1, 'second': 1}]
b=[[0.2, 0.2, 0.2, 0.2, 0.2], [0.16666666666666666, 0.3333333333333333, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666]]
for i, dictionary in enumerate(ld):
for j, key in enumerate(dictionary):
dictionary[key] = b[i][j]
print(ld)
我們遍歷字典並索引它,這樣我們就可以引用列表b
來提取相應的值。
以此為起點,我們現在可以使用列表理解編寫更好的代碼。
new_list = [{key: b[i][j]} for i, dictionary in enumerate(ld) for j, key in enumerate(dictionary)]
在這兩種情況下,我們都得到了預期的輸出:
>>> new_list
[{'this': 0.2}, {'is': 0.2}, {'document': 0.2}, {'the': 0.2}, {'first': 0.2}, {'this': 0.16666666666666666}, {'is': 0.3333333333333333}, {'document': 0.16666666666666666}, {'the': 0.16666666666666666}, {'second': 0.16666666666666666}]
我很樂意回答您可能有的任何其他問題。
編輯
@PacketLoss 正確地指出我的代碼輸出與錯誤混淆。 因此,我們可能會考慮使用collections.OrderedDict
的替代實現。 具體來說,
from collections import OrderedDict
for i, dictionary in enumerate(ld):
dictionary = OrderedDict(dictionary)
for j, key in enumerate(dictionary):
dictionary[key] = b[i][j]
這保持了原始字典的順序完整性。
對於字典,不會保留鍵順序(除非使用 Python 3.6+ )。 這意味着當您嘗試利用列表項的索引將值設置為鍵的順序時,您的數據可能並且將被設置為錯誤的鍵。
鑒於您評論說您有一個包含鍵名的輔助列表。 最好使用它來將數據和鍵的索引映射在一起,然后用這些值更新原始字典。
for indx, values in enumerate(b): # For index, and value in list
data = list(zip(values, klist[indx])) # Zip the elements in your list with the list located at the same index in klist
for row in data: # For tuple in [(0.2, 'this'), (0.2, 'is'), (0.2, 'the'), (0.2, 'first'), (0.2, 'document')]
ld[indx][row[1]] = row[0]
以上所有內容都會更新原始字典中的值,確保兩個列表中的值都映射到正確的鍵,而不是隨機順序。
#[{'this': 0.2, 'is': 0.2, 'the': 0.2, 'first': 0.2, 'document': 0.2}, {'this': 0.16666666666666666, 'document': 0.3333333333333333, 'is': 0.16666666666666666, 'the': 0.16666666666666666, 'second': 0.16666666666666666}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.