![](/img/trans.png)
[英]How to create three separate lists of values from a list of dictionaries where each dictionary has three keys
[英]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.