[英]I was making a random anime selector in python and I can't seem to get where the error is.Could somebody help me out with this project
I have tried searching for a solution but haven't found an answer yet我已尝试寻找解决方案,但尚未找到答案
from random import choice
#create a list of animes and insert their genres
Myanimes= {
"Action":["One Punch Man","Demon Slayer","Vinland Saga","Baki","Baki Hanma","Full Metal alchemist:brotherhood","Yasuke","Dragon Ball Z","Dragon Ball Super"],
"Adventure":["My hero academia "," Black Clover","Naruto","Cowboy Bebop"],
"Supernatural":["Blue exorcist","Jojo's Bizarre Adventure"],
"Sci-fi":["Attack on Titan","Assasination Classroom","Parasyte"],
"Fantasy":["Jujustsu Kaisen","Hunter x Hunter","Devilman Crybaby"],
"Comedy":["Komi Can't Communicate"],
"Drama":["Food Wars","The Disastrous Life of Saiki K"],
"Psychological":["Code Geass","Mob Pyscho","Death Note"],
"Horror":["Castlevania","Record of Ragnarok"],
}
print(choice(Myanimes))
Error:错误:
KeyError: 4
I keep getting a key error 4 but if you find any other errors please help me correct them.我不断收到一个关键错误 4,但如果您发现任何其他错误,请帮助我更正它们。
As said in the comments, random.choice
works with lists and not with dicts.正如评论中所说,
random.choice
适用于列表而不是字典。 You have two options:你有两个选择:
genre=choice(list(Myanimes.keys()))
print(genre, Myanimes[genre])
# Result: Fantasy ['Jujustsu Kaisen', 'Hunter x Hunter', 'Devilman Crybaby']
(key, value)
pairs(key, value)
对print(choice(list(Myanimes.items())))
# Result: ('Supernatural', ['Blue exorcist', "Jojo's Bizarre Adventure"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.