Dictionary Views -- good examples? [was Re: Python 3 dict question]

Ian Kelly ian.g.kelly at gmail.com
Fri May 6 20:23:22 EDT 2011


On Fri, May 6, 2011 at 4:49 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
> Ian Kelly wrote:
>>
>> On Fri, May 6, 2011 at 1:57 PM, dmitrey <dmitrey15 at gmail.com> wrote:
>>>
>>> Unfortunately, it doesn't work, it turn out to be dict_items:
>>>>>>
>>>>>> next({1:2}.items())
>>>
>>> Traceback (most recent call last):
>>>  File "<stdin>", line 1, in <module>
>>> TypeError: dict_items object is not an iterator
>>
>> So call iter() on it first:
>>
>> next(iter(myDict.items()))
>
> Which is becoming less elegant.

That's not even the worst of it.  If the dict is empty, then the code
above will raise a StopIteration, which must be caught locally since
if it propagates it could be swallowed by a generator.  So a full
recipe should really look more like this:

try:
    first_item = next(iter(my_dict.items()))
except StopIteration:
    raise ValueError("empty dict")

> Seems to me that View objects should be directly iterable

They are.  They're just not directly nextable because they're treated
as dependent collections, not iterators.

> but then I don't really understand the motivation behind them or what greatness is facilitated by having them.
>
> Anybody care to chime in with their usage of this construct?

You should start with PEP 3106.  The main idea is that dict.keys() and
dict.items() can be treated as frozensets, while still being more
lightweight than lists.  That lets you do nifty things like "a.keys()
== b.keys()" which, if a and b are Python 3 dicts, will tell you
whether they contain the same keys.

Whether anybody actually uses this, I have no idea.



More information about the Python-list mailing list