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.
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.
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.
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.
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.