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.
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())
Avoiding the whole values
/itervalues
/viewvalues
mess, this works equally well in Python2 or Python3
dictionary[next(iter(dictionary))]
alternatively if you prefer generator expressions
next(dictionary[x] for x in dictionary)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With