'Python dictionaries of sets

I have a dictionary

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

I need to regroup this dictionary as

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

I tried:

fruits = {}
for k, v in boxes.items():
    if (v in fruits):
        fruits[v].add(k)
    else:
        fruits[v] = set()
        fruits[v].add(k)

I get this error: TypeError: unhashable type: 'set', and many other attempts also not working. Please guide ! Thanks



Solution 1:[1]

This is a good case for using setdefault as follows:

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'}}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Albert Winestein