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.
dictionary.itervalues().next()? That would at least be better than your secondarbfunction. - srgergiteritemsnotitervalues/nitpick/ - moooeeeep