How to convert python dict_keys to list ? Get Answer Here!

Convert python dict_keys to list

Are you looking for How to convert python dict_keys to list ? In order to achieve it we use dict.keys() function and typecast in list object. Lets see this implementation step by step.

 

Convert python dict_keys to list –

We will first create the sample dict with some data. Then we will see two different ways to convert python dict keys to list.

Here is the sample dict.

my_dict={
    "key1":1,
    "key2":2,
    "key3":3,
    "key4":4,
    "key5":5,
    "key6":6
}

Method 1 :

Wen we use the dict.keys() function, It will return the dict_keys type object. Now we will type cast explicitly to list type object.

converted_list=list(my_dict.keys())
print(converted_list)

Lets run the above code.

python dict_keys to list
python dict_keys to list

Method 2:

It is little different than Method 1. But we will only replace the typecasting step. Here we will use the iterater and iterrate the dict_keys object and we will also create a empty list. In each iteration we will append the element in the list.

converted_list = list()
for ele in my_dict.keys():
    converted_list.append(ele)

Here is the executed version of the above code.

python dict keys to list appending method
python dict keys to list appending method

 

Method 3:

It will work for python>3.5 . In this Method, We will use “*” before the dict.  It will work as pointer. Firstly lets see the code example.

converted_list=[*my_dict]
python dict keys to list pointer method
python dict keys to list pointer method

 

Difference Between dict_keys() and list –

Well we all know about list. Here will understand about dict_keys() . dict_keys() will make keys iterable. But It is very different from list.

Conclusion –

We all know the python programming language is very popular just because of object compatibility. Also dict is very commonly used in data processing with list. Hence we need to figure out this way for compatibility. Well, I hope now you can easily convert dict keys into list using any of the methods. If you know some other way apart from these,Please comment below in the comment box.

Thanks 

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Abhishek ( Chief Editor) , a data scientist with major expertise in NLP and Text Analytics. He has worked on various projects involving text data and have been able to achieve great results. He is currently manages Datasciencelearner.com, where he and his team share knowledge and help others learn more about data science.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner