簡體   English   中英

如何通過將兩個列表合並在一起來創建字典列表,其中鍵重復

[英]How to create list of dictionaries from merging two lists together, where the keys are repeated

我有兩個清單:

l = [1.1, 1.1, 1.1, 1.1]

keys = [[2, 3, 1, 4], [2, 1, 4, 3], [3, 1, 2, 4], [3, 2, 4, 1]]

我想創建一個字典列表和 output:

d = [{2: 1.1, 3: 1.1, 1: 1.1, 4: 1.1}, {2: 1.1, 1: 1.1, 4: 1.1, 3: 1.1}, {3: 1.1, 1: 1.1, 2: 1.1, 4: 1.1}, {3: 1.1, 2: 1.1, 4: 1.1, 1: 1.1}]

我試過d = [dict(zip(keys, i)) for i in l]

但這會返回TypeError: zip argument #2 must support iteration

任何幫助表示贊賞

對於keys中的每個元素d ,您要創建一個字典,通過使用d壓縮l的每個元素來創建,所以

[dict(zip(d, l)) for d in keys]

您需要遍歷鍵:

l = [1.1, 1.1, 1.1, 1.1]
keys = [[2, 3, 1, 4], [2, 1, 4, 3], [3, 1, 2, 4], [3, 2, 4, 1]]
d = [dict(zip(i, l)) for i in keys]
print(d)

Output:

[{2: 1.1, 3: 1.1, 1: 1.1, 4: 1.1}, {2: 1.1, 1: 1.1, 4: 1.1, 3: 1.1}, {3: 1.1, 1: 1.1, 2: 1.1, 4: 1.1}, {3: 1.1, 2: 1.1, 4: 1.1, 1: 1.1}]

暫無
暫無

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

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