jeudi 22 juin 2017

'dict_keys' object does not support indexing' - Retrieval of random key from dictionary [duplicate]

This question already has an answer here:

color_dic = {"blue": "calm", "red": "angry", "yellow": "happy"]
feellib = ["calm", "angry", "happy", "sad", "excited", "annoyed"]

color = random.choice(color_dic)
feel_update = random.choice(feellib)

color_dic[color] = feel_update

print (color_dic[color])

So what I'm wanting my code to do is select a random color from "color_dic" and then apply a new feeling it. For example it would take the key of blue from "color_dic" and then randomly choose "happy" from "feellib". It would then rewrite {"blue":"calm"} to {"blue":"happy"} . But when I use the code above I get:

color = random.choice(color_dic.keys())
    return seq[i]
TypeError: 'dict_keys' object does not support indexing

I'm able to make this work if I make a separate library of colors in list form:

color_list = ["blue", "red", "yellow"]
color = random.choice(color_list)

The only problem with this is it means I have to update both "color_list" and "color_dic" if I want to add new colors.

Is there any way I can have my code pick a random key from "color_dic"? Any help would be much appreciated!




Aucun commentaire:

Enregistrer un commentaire