Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

In Python 2.7, I could 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'm wondering, is there a better way to return a list in Python 3?

 

1 Answer

0 votes
by (106k points)

The better Pythonic way is to use the list(newdict.keys()), this function will convert the newdict_keys object to a list. That will act as a list for most purposes below is the code that illustrates the use of:-

newdict = {1:0, 2:0, 3:0}

print(list(newdict.keys())

image

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
4 answers

Browse Categories

...