Thursday 7 March 2019

How to return dictionary keys as a list in Python?



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?


Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...