私はthis postを見て、与えられた文字列が辞書の特定の値と一致するかどうか調べる方法を見つけようとしました。私は辞書付きの辞書を持っていますし、私はどのようにして文字列が'warrior'
であれば辞書を見て、サブ辞書の中に入って、指定された文字列のname
キーがあるかどうか確認してください、クラスを返します。これは私のコードです。Python辞書を通し、与えられた文字列がどんな名前の値とも一致するかどうかを調べる
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を返すか返さ持つために何ができますか辞書?
あなた大文字chosenclass。大文字のクラス[i] ["name"]もあります。 – Neo
そして、単純にclasses.values()を反復処理することもできます – Neo
'class [key]'、つまり '' WARRIOR''で反復とインデックスを避けてみませんか? –