Home >Backend Development >Python Tutorial >How to Convert Dict Keys from 'dict_keys' to List in Python 3?
Converting Dict Keys from 'dict_keys' to List
In Python 2.7, obtaining dictionary keys as a list was straightforward using newdict.keys(). However, in Python 3.3 and later, this method returns a dict_keys object instead of a list.
To obtain a plain list of keys with Python 3, you can convert the dict_keys object using list(newdict.keys()). This will generate a list of keys that can be manipulated as needed.
Should You Convert?
While converting the dict_keys object to a list is possible, it's worth considering whether it's necessary. In most cases, the dict_keys object behaves similarly to a list. It supports iteration, allowing you to access and process keys efficiently.
For example:
for key in newdict.keys(): print(key)
The above code will iterate over the keys of the newdict dictionary and print each key.
Extending Dict Keys
It's important to note that the dict_keys object does not support insertion of new keys using newdict[k] = v. If you need to add new keys to your dictionary, use the standard dict methods such as update() or setdefault().
The above is the detailed content of How to Convert Dict Keys from 'dict_keys' to List in Python 3?. For more information, please follow other related articles on the PHP Chinese website!