Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python遍历字典,确定给定字符串是否与任何名称值匹配_Python_Dictionary - Fatal编程技术网

Python遍历字典,确定给定字符串是否与任何名称值匹配

Python遍历字典,确定给定字符串是否与任何名称值匹配,python,dictionary,Python,Dictionary,我通读了一遍,试图找出如何找出给定字符串是否与字典中的某个值匹配,但它没有返回任何内容。我有一个包含字典的字典,我正试图找出我如何才能,比如说如果给定一个字符串'warrior',查看字典,进入子字典,检查给定字符串的name键,如果它存在,返回类。这是我的密码 类.py player.py 如何让它在字典中搜索,如果chosenClass是现有的类字典,则返回true或返回字典 .... #this returns nothing for key, value in class

我通读了一遍,试图找出如何找出给定字符串是否与字典中的某个值匹配,但它没有返回任何内容。我有一个包含字典的字典,我正试图找出我如何才能,比如说如果给定一个字符串
'warrior'
,查看字典,进入子字典,检查给定字符串的
name
键,如果它存在,返回类。这是我的密码

类.py player.py 如何让它在字典中搜索,如果
chosenClass
是现有的类字典,则返回true或返回字典

....
    #this returns nothing
    for key, value in classes.items():
        if value == chosenClass:
我认为您应该将
chosenClass
进行比较,而不是将该循环中的
进行比较。一个简单的故障排除工具是打印内容以查看发生了什么

....
    #this returns nothing
    for key, value in classes.items():
        print('key:{}, value:{}, chosenClass:{}'.format(key, value, chosenClass)
        if value == chosenClass:
但也许更简单的方法是:

def setClass(chosenClass):
    chosenClass = chosenClass.upper()
    chosen = classes.get(chosenClass, False)
    return chosen

你可以选择大写的chosenclass。大写类[i][“name”]也是。顺便说一句,你也可以简单地在类上迭代。value()为什么不直接避免迭代并通过
类[key]
索引,即
战士“
?@RyanStein这很有意义。我换了它,它就工作了。谢谢作为答案发布,我将投票并接受。只是好奇,添加
False
有什么作用?如果
chosenClass
不在
classes
中,
.get()
将返回
False
,它将被分配给
所选的
....
    #this returns nothing
    for key, value in classes.items():
        print('key:{}, value:{}, chosenClass:{}'.format(key, value, chosenClass)
        if value == chosenClass:
def setClass(chosenClass):
    chosenClass = chosenClass.upper()
    chosen = classes.get(chosenClass, False)
    return chosen