Python迭代字典,确定给定的字符串是否匹配任何名称值

时间:2017-10-12 16:38:57

标签: python dictionary

我查看this post试图弄清楚如何找出一个给定的字符串是否与字典中的某个值相匹配,但它什么都没有丢回。我有一本带字典的字典,我想弄清楚我是怎么做的,让我们说如果给出一个字符串'warrior',查看字典,进入子字典,查看name键给定的字符串,如果存在,则返回该类。这是我的代码。

classes.py

#import playerstats
from player import playerStats

def setClass(chosenClass):
    chosenClass = chosenClass.upper()
    #function from post
    """print ([key
              for key, value in classes.items()
              if value == chosenClass])"""
    #this returns nothing
    for key, value in classes.items():
        if value == chosenClass:
            print(classes[chosenClass][value])
    #also returns nothing
    for i in classes:
        if classes[i]["name"] == chosenClass:
            print('true')

#create classes
classes = {
    'WARRIOR': {
        #define name of class for reference
        'name': 'Warrior',
        #define description of class for reference
        'description': 'You were  born a protector. You grew up to bear a one-handed weapon and shield, born to prevent harm to others. A warrior is great with health, armor, and defense.',
        #define what the class can equip
        'gearWeight': ['Cloth', 'Leather', 'Mail', 'Plate'],
        #define stat modifiers
        'stats': {
            #increase, decrease, or leave alone stats from default
            'maxHealth': playerStats['maxHealth'],
            'stamina': playerStats['stamina'] * 1.25,
            'resil': playerStats['resil'] * 1.25,
            'armor': playerStats['armor'] * 1.35,
            'strength': playerStats['strength'] * 0.60,
            'agility': playerStats['agility'],
            'criticalChance': playerStats['criticalChance'],
            'spellPower': playerStats['spellPower'] * 0.40,
        }
    }
}

player.py

import random
import classes

#set starter gold variable
startGold = random.randint(25,215)*2.5
#begin player data for new slate
playerStats = {
    'currentHealth': int(100),
    'maxHealth': int(100),
    'stamina': int(10),
    'resil': int(2),
    'armor': int(20),
    'strength': int(15),
    'agility': int(10),
    'criticalChance': int(25),
    'spellPower': int(15),
    #set gold as random gold determined from before
    'gold': startGold,
    'name': {'first': 'New', 'last': 'Player'},
}

如何让它搜索字典,如果chosenClass是现有的类字典,返回true或返回字典?

1 个答案:

答案 0 :(得分:1)

....
    #this returns nothing
    for key, value in classes.items():
        if value == chosenClass:

我认为您应该将keychosenClass进行比较,而不是在该循环中将value进行比较。一个简单的故障排除工具是打印 stuff 以查看正在发生的事情

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