tags:

views:

206

answers:

3

If dict is not empty, the way I use to access 1st element in dict is:

dict[dict.keys()[0]]

Is there any better way to do this? Thanks.

+3  A: 

Non-destructively you can:

dict.itervalues().next()

On Python 3 this becomes

next (iter (dict.values()))

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 = dict.popitem()

Note that "first" is not an appropriate term here. This is "any" item, because dict is not an ordered type.

doublep
Don't you mean `dict.iterkeys().next()`?
John Machin
@John Machin: Well, the question seems to access value associated with the first key, so that's what I do in the answer as well.
doublep
I ended up using dict.popitem(), that's exactly I am looking for. Thanks to everyone.
Stan
+2  A: 

As others mentioned, there is no "first item", since dictionaries have no guaranteed order (they're implemented as hash tables). If you want, for example, the value corresponding to the smallest key, thedict[min(thedict)] will do that. If you care about the order in which the keys were inserted, i.e., by "first" you mean "inserted earliest", then in Python 3.1 you can use collections.OrderedDict, which is also in the forthcoming Python 2.7; for older versions of Python, download, install, and use the ordered dict backport (2.4 and later) which you can find here.

Alex Martelli
+1  A: 

Ignoring issues surrounding dict ordering, this might be better:

next(dict.itervalues())

This way we avoid item lookup and generating a list of keys that we don't use.

Matt Joiner
values() will make a copy of all values (as will keys() for keys), so this will make many operations O(n^2).
Glenn Maynard
So will the OPs version? I'll change this to use an iterator then.
Matt Joiner