HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How do I return dictionary keys as a list in Python?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howreturnkeyslistdictionarypython

Problem

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

>>> newdict = {1:0, 2:0, 3:0}
>>> newdict.keys()
[1, 2, 3]


With Python >= 3.3, I get:

>>> newdict.keys()
dict_keys([1, 2, 3])


How do I get a plain list of keys with Python 3?

Solution

This will convert the dict_keys object to a list:

list(newdict.keys())


On the other hand, you should ask yourself whether or not it matters. It is Pythonic to assume duck typing -- if it looks like a duck and it quacks like a duck, it is a duck. The dict_keys object can be iterated over just like a list. For instance:

for key in newdict.keys():
    print(key)


Note that dict_keys doesn't support insertion newdict[k] = v, though you may not need it.

Code Snippets

list(newdict.keys())
for key in newdict.keys():
    print(key)

Context

Stack Overflow Q#16819222, score: 1715

Revisions (0)

No revisions yet.