Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to return dictionary keys as a list in Python-3.x ?

In Python 2.7, I get dictionary keys, values, or items as a list:

>>> newdict = {1:0, 2:0, 3:0}
>>> newdict.keys()
[1, 2, 3]
Now, in Python >= 3.3, I get something like this:


>>> newdict.keys()
dict_keys([1, 2, 3])
So, I have to do this to get a list:


newlist = list()
for i in newdict.keys():
newlist.append(i)

I was thinking , is there a better way to return a list in Python 3?
by

2 Answers

kshitijrana14
Try list(newdict.keys()).
This will convert the dict_keys object to a list.
On the other hand, you should ask yourself whether or not it matters. The Pythonic way to code is to assume duck typing (if it looks like a duck and it quacks like a duck, it's a duck). The dict_keys object will act like a list for most purposes. For instance:
for key in newdict.keys():
print(key)

Obviously, insertion operators may not work, but that doesn't make much sense for a list of dictionary keys anyway.
RoliMishra
list(newdict) works in both Python 2 and Python 3, providing a simple list of the keys in newdict. keys() isn't necessary.

Login / Signup to Answer the Question.