Python dictionary.keys() error

tokageKitayama picture tokageKitayama · Jan 21, 2012 · Viewed 89.7k times · Source

I am trying to use the .keys() and instead of getting a list of the keys like always have in the past. However I get this.

b = { 'video':0, 'music':23 }
k = b.keys()
print( k[0] )

>>>TypeError: 'dict_keys' object does not support indexing

print( k )
dict_keys(['music', 'video'])

it should just print ['music', 'video'] unless I'm going crazy.

What's going on?

Answer

Fred Foo picture Fred Foo · Jan 21, 2012

Python 3 changed the behavior of dict.keys such that it now returns a dict_keys object, which is iterable but not indexable (it's like the old dict.iterkeys, which is gone now). You can get the Python 2 result back with an explicit call to list:

>>> b = { 'video':0, 'music':23 }
>>> k = list(b.keys())
>>> k
['music', 'video']

or just

>>> list(b)
['music', 'video']