Access an arbitrary element in a dictionary in Python

Stan picture Stan · Jun 23, 2010 · Viewed 481.4k times · Source

If a mydict is not empty, I access an arbitrary element as:

mydict[mydict.keys()[0]]

Is there any better way to do this?

Answer

doublep picture doublep · Jun 23, 2010

On Python 3, non-destructively and iteratively:

next(iter(mydict.values()))

On Python 2, non-destructively and iteratively:

mydict.itervalues().next()

If you want it to work in both Python 2 and 3, you can use the six package:

six.next(six.itervalues(mydict))

though at this point it is quite cryptic and I'd rather prefer your code.

If you want to remove any item, do:

key, value = mydict.popitem()

Note that "first" may not be an appropriate term here because dict is not an ordered type in Python < 3.6. Python 3.6+ dicts are ordered.