Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to access arbitrary element from dictionary [duplicate]

Tags:

python

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.

like image 822
Oddthinking Avatar asked May 15 '12 03:05

Oddthinking


2 Answers

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()) 
like image 102
happydave Avatar answered Sep 20 '22 15:09

happydave


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) 
like image 45
John La Rooy Avatar answered Sep 21 '22 15:09

John La Rooy