Reputation: 584
I looked through this post trying to figure out how to find out if a given string matches a certain value in a dictionary, but it's throwing nothing back. I have a dictionary with dictionaries and I'm trying to figure out how I can, let's say if given a string 'warrior'
, look through the dictionary, go inside the sub dictionary, check the name
key for the given string, and if it exists, return the class. This is my code.
#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,
}
}
}
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'},
}
What can I do to have it search through the dictionary, and if chosenClass
is an existing class dictionary, return true or return the dictionary?
Upvotes: 0
Views: 837
Reputation: 23773
....
#this returns nothing
for key, value in classes.items():
if value == chosenClass:
I think you should be comparing the key
to chosenClass
, instead of the value
in that loop. An easy troubleshooting tool is to print stuff to see what is happening
....
#this returns nothing
for key, value in classes.items():
print('key:{}, value:{}, chosenClass:{}'.format(key, value, chosenClass)
if value == chosenClass:
But maybe an easier way to do it is:
def setClass(chosenClass):
chosenClass = chosenClass.upper()
chosen = classes.get(chosenClass, False)
return chosen
Upvotes: 1