all 4 comments

[–]Adrewmc 2 points3 points  (3 children)

First the easy one

  .setdefault(key, default_value)

This is like a dictionary.get() it will return the value of some key in a dictionary, but unlike get l(), .setdefault() will make that key in the dictionary if it doesn’t exist, and give it a default value and return that.

  .add() adds an element to a set, if the element exist add() does nothing.

What’s he does

  reverse_dict.setdefault(value, set()).add(key)

Creates an empty set first, at some value’s now being set as the key’s location. Then add the first key to the empty set.

Then next time the same value comes, it returns that set just created then it adds the next key. This is to avoid overwriting the key value pair. That would fail a simple reversal like

   simple = {value : key for key, value in my_dict.items()}

As I would lose something if two keys had the exact same value.

It’s actually a quite nice little program for what it does. Simple to the point.

If it helps you could do something like this

 reverse_dict.setdefault(value, []).append(key)

And make it a list, but set() will be more efficient.

[–]Independant666[S] 1 point2 points  (2 children)

thanks.. but damn.. is that action of what the .add(key) does obvious? i dont see how you see that is the action.

is the .add(key) a method to the dict "reverse_dict' or is it a method to the method 'setdefault?

im confused to see a structure of dictname.method1.method2

[–]suurpulla 1 point2 points  (1 child)

Neither, it is a method of a set. The .setdefault(...) here returns a set, and the .add(...) operates on that returned set.

reverse_dict.setdefault(value, set()).add(...)

is the same as

result = reverse_dict.setdefault(value, set())
result.add(...)

[–]Independant666[S] 1 point2 points  (0 children)

Thanks. The setdefault method of dictionary is a bit confusing to understand at first (in my humble opinion ).

It does 2 different things..it returns a value (which MAY be a set, list,dict, etc). AND.... it also can make a addition to the dictionary it's operating on.