[Tutor] Lists of duplicates

Alex Kleider akleider at sonic.net
Thu Mar 9 01:06:31 EST 2017


On 2017-03-08 21:14, boB Stepp wrote:

> Alex, I think you can break this down as follows:
> 
> py3: res = {}
> py3: def key_item_to_res(item):
> ...     res.setdefault(item, []).append(item)
> ...
> py3: key_item_to_res(3)
> py3: res
> {3: [3]}
> py3: key_item_to_res(3)
> py3: res
> {3: [3, 3]}
> py3: key_item_to_res(2)
> py3: res
> {3: [3, 3], 2: [2]}
> 
> I think you can play with this and see how Alan's code works.  The
> setdefault(item, []) method checks the dictionary it is acting on for
> the key, "item".  If it finds it then it will execute the
> "append(item)" method on the sublist attached to that key.  If it does
> not find it, then it creates a new key, "item", attaches the empty
> list, "[]", to that key, and then appends item to that empty list.
> 
> 
> boB

It seems you are simply kicking the can down the road rather than 
explaining how it it is that dot notation actually works.
To access a dictionary item one must specify it by name_of_dict[key].
What Allan is (and you also are) doing is using dot notation.
Your example uses side effects (which I've been lead to believe is a no 
no.)
The dot notation works (to my surprise) and I was hoping for an 
explanation of just what is happening.

a




More information about the Tutor mailing list