pythonpython-3.xdictionarydictview

dict.keys()[0] on Python 3


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


Solution

  • 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.