Python 3 dict question

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


On Fri, May 6, 2011 at 1:51 PM, Chris Rebert <clp2 at rebertia.com> wrote:
> On Fri, May 6, 2011 at 12:40 PM, dmitrey <dmitrey15 at gmail.com> wrote:
>> hi all,
>> suppose I have Python dict myDict and I know it's not empty.
>> I have to get any (key, value) pair from the dict (no matter which
>> one) and perform some operation.
>> In Python 2 I used mere
>> key, val = myDict.items()[0]
>> but in Python 3 myDict.items() return iterator.
>> Of course, I could use
>> for key, val in myDict.items():
>>   do_something
>>   break
>> but maybe there is any better way?
>
> key, val = next(myDict.items())

Recognizing that if myDict is empty then this will raise StopIteration
instead of KeyError.



More information about the Python-list mailing list