0 votes
1 view
in Python by (47.7k 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 (107k 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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...