Access an arbitrary element in a dictionary in Python


Question

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

mydict[mydict.keys()[0]]

Is there any better way to do this?

1
454
5/16/2018 3:59:24 PM

Accepted Answer

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" is not an appropriate term here. This is "any" item, because dict is not an ordered type.

531
5/16/2018 4:04:26 PM

If you only need to access one element (being the first by chance, since dicts do not guarantee ordering) you can simply do this in Python 2:

my_dict.keys()[0]     -> key of "first" element
my_dict.values()[0]   -> value of "first" element
my_dict.items()[0]    -> (key, value) tuple of "first" element

Please note that (at best of my knowledge) Python does not guarantee that 2 successive calls to any of these methods will return list with the same ordering. This is not supported with Python3.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon