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

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Sun May 8 05:23:48 EDT 2011


Am 07.05.2011 11:09, schrieb Gregory Ewing:
> Ethan Furman wrote:
>> Ian Kelly wrote:
>>
>>> next(iter(myDict.items()))
>>
>> Which is becoming less elegant.
>
> If you're doing this sort of thing a lot you can make
> a little helper function:
>
> def first(x):
> return next(iter(x))
>
> then you get to say
>
> first(myDict.items())

... and get a StopIteration if the dict is empty.

If you do

def first(x, default=None):
     for i in x:
         return i
     return default

you might have an alternative approach to do so.


Thomas



More information about the Python-list mailing list