I have a Python function that takes as arguments a player's name and score and determines whether this is the player's highest score. It does so by comparing the arguments against a shelve object.
The shelve should only store the high score for each player; there should not be to scores for someone named "Joe" for example.
Unfortunately, I can't figure out how to isolate a dict from the list of dicts (shelf) for comparison against the incoming player dict.
Here's my code:
import shelve
import os
def highscore(player_name, player_score):
"""
Function to return the high score from our
persistent storage of score records for a given
person.
"""
# Get our working directory
working_dir = os.getcwd()
# Create our shelf object for a player
highscore_fn = os.path.join(working_dir, 'highscore.shelve')
# Set our player info
player = {'name': player_name, 'score': player_score}
with shelve.open(highscore_fn, writeback=True) as shelf:
# Check if any records exist in the shelf
if len(shelf) == 0:
# Assign the shelf to an empty list
shelf['player_data'] = []
# Append player data to shelf
shelf['player_data'].append(player)
# Current high score for player
high_score = player.get('score')
else:
# Loop through our player data list
for data in shelf['player_data']:
# Check to see if we have data for a player
if player['name'] in data['name']:
existing_record = data
# Compare the player's new score against previous score
if player.get('score') > existing_record.get('score'):
high_score = player.get('score')
# Update our record for the player
existing_record.update(player)
else:
high_score = existing_record.get('score')
else:
high_score = player.get('score')
shelf['player_data'].append(player)
# Return the high score
return high_score
Any tips would be appreciated!