Home > Enterprise >  Python dictionaries of sets
Python dictionaries of sets

Time:05-09

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

CodePudding user response:

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