-1

I have a dictionary in Python with some keys and their values. like-

states = {"Rajasthan": "Jaipur", "Madhyapradesh" :"Bhopal", "Maharashtra" : "Mumbai", "Tamilnadu": "Chennai" }

I want to retrieve list of all keys of this dictionary like -

["Rajasthan", "Madhyapradesh", "Maharashtra", "Tamilnadu"]

How can i do this.

mksmahi
  • 53
  • 1
  • 3
  • ```x = [key for key,value in states.items()]``` – Hozayfa El Rifai May 19 '20 at 10:22
  • 3
    Does this answer your question? [How to return dictionary keys as a list in Python?](https://stackoverflow.com/questions/16819222/how-to-return-dictionary-keys-as-a-list-in-python) – DavidG May 19 '20 at 10:27
  • It's good to ask questions. But please do sufficient google search first. This is a duplicate of https://stackoverflow.com/questions/16819222/how-to-return-dictionary-keys-as-a-list-in-python. Other resources: [[1](https://www.geeksforgeeks.org/python-get-dictionary-keys-as-a-list/)], [[2](https://www.geeksforgeeks.org/python-dictionary-keys-method/)]. And I got all this from first three results in a single google search! – CypherX May 19 '20 at 10:28

1 Answers1

0

You can use list comprehension as following

keys = [i for i in states]

or
using list function that will convert states keys to a list

list(states)

and you will get

['Rajasthan', 'Madhyapradesh', 'Maharashtra', 'Tamilnadu']
Leo Arad
  • 4,452
  • 2
  • 6
  • 17