Python 3 dict question

dmitrey dmitrey15 at gmail.com
Fri May 6 15:57:11 EDT 2011


On May 6, 10:51 pm, Chris Rebert <c... at rebertia.com> wrote:
> On Fri, May 6, 2011 at 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?
>
> key, val = next(myDict.items())
>
> Cheers,
> Chris

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
>>> dir({1:2}.items())
['__and__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__gt__',
'__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
'__ne__', '__new__', '__or__', '__rand__', '__reduce__',
'__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__',
'__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__',
'__xor__', 'isdisjoint']



More information about the Python-list mailing list