If a mydict
is not empty, I access an arbitrary element as:
mydict[mydict.keys()[0]]
Is there any better way to do this?
On Python 3, non-destructively and iteratively:
next(iter(mydict.values()))
On Python 2, non-destructively and iteratively:
mydict.itervalues().next()
If you want it to work in both Python 2 and 3, you can use the six
package:
six.next(six.itervalues(mydict))
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 = mydict.popitem()
Note that "first" may not be an appropriate term here because dict
is not an ordered type in Python < 3.6. Python 3.6+ dicts
are ordered.