mydict is not empty, I access an arbitrary element as:
Is there any better way to do this?
On Python 3, non-destructively and iteratively:
On Python 2, non-destructively and iteratively:
If you want it to work in both Python 2 and 3, you can use the
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" is not an appropriate term here. This is "any" item, because
dict is not an ordered type.
If you only need to access one element (being the first by chance, since dicts do not guarantee ordering) you can simply do this in Python 2:
my_dict.keys() -> key of "first" element my_dict.values() -> value of "first" element my_dict.items() -> (key, value) tuple of "first" element
Please note that (at best of my knowledge) Python does not guarantee that 2 successive calls to any of these methods will return list with the same ordering. This is not supported with Python3.