Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary.keys() error

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?

like image 809
tokageKitayama Avatar asked Jan 21 '12 14:01

tokageKitayama


People also ask

How do I fix key errors in Python?

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.

What is key error in Python dictionary?

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.

How do you check if a key exists in a dictionary Python?

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.

What is the use of keys () method in a dictionary?

The keys() method extracts the keys of the dictionary and returns the list of keys as a view object.


2 Answers

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'] 
like image 98
Fred Foo Avatar answered Oct 13 '22 00:10

Fred Foo


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.

like image 36
NPE Avatar answered Oct 13 '22 00:10

NPE