Access an arbitrary element in a dictionary in Python
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" may not be an appropriate term here because
dict is not an ordered type in Python < 3.6. Python 3.6+
dicts are ordered.
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" elementmy_dict.values() -> value of "first" elementmy_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.
in Python 3:
list(my_dict.keys()) -> key of "first" elementlist(my_dict.values()) -> value of "first" elementlist(my_dict.items()) -> (key, value) tuple of "first" element
In python3, The way :
return a value in type : dict_keys(), we'll got an error when got 1st member of keys of dict by this way:
dict.keys()TypeError: 'dict_keys' object does not support indexing
Finally, I convert dict.keys() to list @1st, and got 1st member by list splice method: