Python: Is There a Way to Get a List of All the Keys in a Dictionary? If So, How Would You Do It?

Python Question – 4

Is There a Way to Get a List of All the Keys in a Dictionary? If So, How Would You Do It?

I am writing a python program that will be used to get a list of all the keys in a dictionary. I’m using python 2.7.3.
I have the following code:
import operator
for key, value in d.iteritems():
print(key, value)

In the above code, I’m trying to get the key and value that are in the dictionary. How do I do that?
I know this is very basic, but I’m new to python and I’d be grateful if someone could help me out.

A:

Code:

You can use a list comprehension to get all the values:
d['keys']
If you want to get only the keys:
keys = d['keys'].split()
EDIT:
If your keys are of the same length, you can also use a set:
set(d['key'].items())

Leave a Reply

Your email address will not be published. Required fields are marked *