[英]Returning dict from dict comprehension of nested list
my_list = [ [1,2], [2,3], [3,4] ]
# my attempt
output = { {'a':k[0], 'b':k[1]} for k in my_list }
#desired output
[ {a:1, b:2}, {a:2, b:3}, {a:3,b:4} ]
有沒有辦法讓dict理解力返回具有多個鍵的dict?
也許您想這樣做:
output = [ {'a':k[0], 'b':k[1]} for k in my_list ]
# ^ ^
我們在python中稱其為列表理解。
您的外部結構應該是輸出的列表,並且您錯誤地嘗試執行集合理解而不是列表理解。 這失敗了,因為set元素必須是可哈希的,並且dict不可更改,因為它們是可變的。 此外,在這種情況下,您可以打開列表項的包裝以使其更加清晰。
>>> [dict(a=x, b=y) for x, y in my_list]
[{'a': 1, 'b': 2}, {'a': 2, 'b': 3}, {'a': 3, 'b': 4}]
my_list = [ [1,2], [2,3], [3,4] ]
[dict(zip(['a', 'b'], x)) for x in my_list]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.