Frage

i have a yml file that reads like this

RealBank:
  Players:
    player1:
      Balance: '0'
    player2:
      Balance: '0'
    player3:
      Balance: 63050

i can get python to print out each player name. but for the life of me i cannot take that playername, and get their balance to print up.

my code looks like this:

stream = open("config.yml", "r")
doc = yaml.load(stream)
beans = doc['RealBank']['Players']
for bean in beans:
    print bean
    print doc['RealBank']['Players']['%s']['Balance'] % bean  #this command does not work, no matter how i try to assemble it.

this gives me a list of each players name in the yaml file. but i've tried everything i can think of and search for to try and make it so i can take that players name and insert it into another search for their balance.

i know its probably something super simple that im probably overlooking and just not thinking of the right phrase to google and will probably be facepalming half an hour once someone points it out.

War es hilfreich?

Lösung

doc consists of just plain Python builtin types. You're not really querying anything.

That line that isn't working is trying to format the result of doc['RealBank']['Players']['%s']['Balance'], with %s being the literal key name. If you want to use bean as a key, then just pass in the variable:

print doc['RealBank']['Players'][bean]['Balance']

You could also use .items() to iterate over key, value tuples:

for name, player in doc['RealBank']['Players'].items():
    print name, player['Balance']
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top