Pythonic way to access arbitrary element from dictionary

python

Solution

Similar to your second solution, but slightly more obvious, in my opinion:

return next(iter(dictionary.values()))

This works in python 2 as well as in python 3, but in python 2 it's more efficient to do it like this:

return next(dictionary.itervalues())

Problem

I have a dictionary, full of items. I want to peek at a single, arbitrary item: ``` print("Amongst our dictionary's items are such diverse elements as: %s" % arb(dictionary)) ``` I don't care which item. It doesn't need to be random. I can think of many ways of implementing this, but they all seem wasteful. I am wondering if any are preferred idioms in Python, or (even better) if I am missing one. ``` def arb(dictionary): # Creates an entire list in memory. Could take a while. return list(dictionary.values())[0] def arb(dictionary): # Creates an entire iterator. An improvement. for item in dictionary.values(): return item def arb(dictionary): # No iterator, but writes to the dictionary! Twice! key, value = dictionary.popitem() dictionary[key] = value return value ``` I'm in a position where the performance isn't critical enough that this matters (yet), so I can be accused of premature optimization, but I am trying to improve my Python coding style, so if there is an easily understood variant, it would be good to adopt it.

Original source

Related problems