Python 3 dict question

Raymond Hettinger python at rcn.com
Tue May 10 13:25:54 EDT 2011


On May 6, 12:40 pm, dmitrey <dmitre... 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?

If your use case allows the item to be removed, then use:

   key, val = myDict.popitem()

Otherwise, use:

   key, val = next(iter(MyDict.items()))

The latter is nice because next() allows you to supply a default
argument in case the dictionary is emtpy:

   key, val = next(iter(MyDict.items()), (None, None))

Raymond

---------
follow my tips and recipes on twitter: @raymondh





More information about the Python-list mailing list