Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dict.keys()[0] on Python 3 [duplicate]

I have this sentence:

def Ciudad(prob):     numero = random.random()     ciudad = prob.keys()[0]     for i in prob.keys():         if(numero > prob[i]):             if(prob[i] > prob[ciudad]):                 ciudad = i         else:             if(prob[i] > prob[ciudad]):                 ciudad = i      return ciudad 

But when I call it this error pops:

TypeError: 'dict_keys' object does not support indexing 

is it a version problem? I'm using Python 3.3.2

like image 925
Menticolcito Avatar asked Sep 08 '13 18:09

Menticolcito


People also ask

Can keys be duplicate in dictionary Python?

Python dictionary doesn't allow key to be repeated.

Can dictionary have duplicate key values?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.


1 Answers

dict.keys() is a dictionary view. Just use list() directly on the dictionary instead if you need a list of keys, item 0 will be the first key in the (arbitrary) dictionary order:

list(prob)[0] 

or better still just use:

next(iter(dict)) 

Either method works in both Python 2 and 3 and the next() option is certainly more efficient for Python 2 than using dict.keys(). Note however that dictionaries have no set order and you will not know what key will be listed first.

It looks as if you are trying to find the maximum key instead, use max() with dict.get:

def Ciudad(prob):     return max(prob, key=prob.get) 

The function result is certainly going to be the same for any given prob dictionary, as your code doesn't differ in codepaths between the random number comparison branches of the if statement.

like image 73
Martijn Pieters Avatar answered Oct 04 '22 18:10

Martijn Pieters