[英]Dictionary Comprehension with a set of Tuple as value
我有這個
dict_1 = {1:{("Apple",1),("Orange",1),("Banana",1),("Lemon",1)}}
我想要這個:
{"Apple","Orange","Banana","Lemon"}
這里的正確理解是什么。
我的嘗試失敗了,因為
TypeError:不可散列的類型:'set'
意味着我無法打開套裝。
如果您在字典中只有一個鍵名1
,您可以簡單地使用
dict = {1:{("Apple",1),("Orange",1),("Banana",1),("Lemon",1)}}
{key for key, val in dict[1]} # used the 1 assuming its the only key
Output:
{"Apple","Orange","Banana","Lemon"}
編輯:
具有任意數量變量(鍵)的代碼
dict = {1:{("Apple",1),("Orange",1),("Banana",1),("Lemon",1)},2:{("Apple",1),("Orange",1),("Banana",1),("Lemon",1)}}
resultArray = [{x for x, y in dict[eachkey]} for eachkey in {x for x, y in dict.items()} ]
print(resultArray)
Output:
[{'Orange', 'Apple', 'Lemon', 'Banana'}, {'Orange', 'Apple', 'Lemon', 'Banana'}]
編輯2:
代碼:
from itertools import chain
dict = {1:{("Apple",1),("Orange",1),("Banana",1),("Lemon",1)},2:{("Juice",1),("Cocktail",1),("Milk",1),("Soup",1)}}
resultArray = [{x for x, y in dict[eachkey]} for eachkey in {x for x, y in dict.items()} ]
print(set().union(*(resultArray)))
Output:
{'Lemon', 'Soup', 'Milk', 'Cocktail', 'Banana', 'Apple', 'Orange', 'Juice'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.