簡體   English   中英

Python 集合字典

[英]Python dictionaries of sets

我有一本字典

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',許多其他嘗試也無效。 請指導! 謝謝

這是使用 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)

Output:

{'apples': {'box 1'}, 'mangoes': {'box 2', 'box 4'}, 'oranges': {'box 3'}}

暫無
暫無

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

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