Author | Message |
---|---|
wcwir
Posts: 75
|
Posted 10:53 Jan 28, 2019 |
I was in the back of a class so didn't see what Jay picked as type of hands.items(), but I think I heard "list" mentioned. I checked, the type is class dict_items, and I wondered: why Python would make special class when list would do? The explanation I got comes from Reddit, so should be verified: ----
A list has to load all its data into memory before doing anything. These objects just reference the underlying dict, not duplicating anything. This means that they are less memory-hungry and that, if you are apt to exit the loop quickly, you didn't pay to copy everything beforehand. --- So OK, this dict_items is more efficient than creating a list. Something to keep in mind: --- Besides the memory savings, an important detail is that when the underlying dict changes, the dict views reflect these changes, whereas a list would not. --- This may be a problem! If you want to make sure that the dictionary you are iterating over doesn't change during the iteration (which it might in a parallel situation), do list(hands.items()) (and suffer performance hit).
|
wcwir
Posts: 75
|
Posted 11:00 Jan 28, 2019 |
Also note: dict_items() is not a sequence -- it does not support indexing. |
jpatel77
Posts: 44
|
Posted 12:30 Jan 28, 2019 |
You are right, I should have been clearer there. What python returns is just a view of an object (dict in this case) that is iterable as a tuple consisting of key and the value. However it wasn’t used to be like this before. In Python 2.x, all standard methods like items(), keys(), values() used to return a list consisting of values. It wasn’t until when the generators were introduced that Python 2.x added more generator based methods i.e. iteritems(), iterkeys(), itervalues(). But in Python 3, the old impl for standard methods were replaced with views, so now items() in Python 3 no longer returns a complete independent list, rather it returns a view object that acts just like a window to see things differently or in a different way. And then these capabilities were backported to Python 2 as viewitems() later on. Since these views do not hold a separate copy of data, it is dynamic in nature. |
rabbott
Posts: 1649
|
Posted 12:38 Jan 28, 2019 |
Thanks for the information and discussion. I didn't know any of that! |