我有一本字典
boxes {
'box 1' : 'apples',
'box 2' : 'mangoes',
'box 3' : 'oranges',
'box 4' : 'mangoes'
}
我需要將這本字典重新組合為
fruits {
'apples' : {'box 1' },
'mangoes' : {'box 2', 'box 4'},
'oranges' : {'box 3'}
}
我試過:
fruits = {}
for k, v in boxes.items():
if (v in fruits):
fruits[v].add(k)
else:
fruits[v] = set()
fruits[v].add(k)
我收到此錯誤:TypeError: unhashable type: 'set',以及許多其他嘗試也不起作用。請指導!謝謝
uj5u.com熱心網友回復:
這是使用 setdefault 的一個很好的例子,如下所示:
boxes = {
'box 1' : 'apples',
'box 2' : 'mangoes',
'box 3' : 'oranges',
'box 4' : 'mangoes'
}
fruits = dict()
for k, v in boxes.items():
fruits.setdefault(v, set()).add(k)
print(fruits)
輸出:
{'apples': {'box 1'}, 'mangoes': {'box 2', 'box 4'}, 'oranges': {'box 3'}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471965.html
