Home >Backend Development >Python Tutorial >How to Get a List of Dictionary Keys in Python 2.7 and 3 ?
In Python, accessing dictionary keys as a list often encounters differences between Python 2.7 and versions 3.3 and above. While Python 2.7 conveniently returns a list of keys with newdict.keys(), Python from 3.3 onwards encapsulates the keys in a dict_keys object.
To obtain a plain list of keys in Python 3, employ the list() function to convert the dict_keys object:
list(newdict.keys())
This will transform the encapsulated dict_keys into a standard list.
However, it's essential to consider whether this conversion truly matters. Python embraces duck typing, meaning if an object acts and responds like a list, its exact type becomes less significant. The dict_keys object can be subjected to list-like iterations:
for key in newdict.keys(): print(key)
This performs key iteration just as well as a regular list. Notably, the dict_keys object lacks the ability to insert new elements via newdict[k] = v, but this may not be a necessity in many use cases.
The above is the detailed content of How to Get a List of Dictionary Keys in Python 2.7 and 3 ?. For more information, please follow other related articles on the PHP Chinese website!