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?
How to Fix the KeyError in Python Using the in Keyword. We can use the in keyword to check if an item exists in a dictionary. Using an if...else statement, we return the item if it exists or return a message to the user to notify them that the item could not be found.
The Python KeyError is a type of LookupError exception and denotes that there was an issue retrieving the key you were looking for. When you see a KeyError , the semantic meaning is that the key being looked for could not be found.
Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.
The keys() method extracts the keys of the dictionary and returns the list of keys as a view object.
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']
If you assigned k
like so:
k = list(b.keys())
your code will work.
As the error says, the dict_keys
type does not support indexing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With