0
highscore = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10}

To give context, I am making a game that has a scoreboard. After the game, if the player's score is higher than the highest value in the dictionary, the lowest value would be removed. The keys in this dictionary are example player names

For example, if a new player (who we will call 'L') scores 11 points, 'a' (with a score of 1) would be removed.

Any suggestions? I appreciate any and all suggestions, even negative ones

Kelven Lim
  • 73
  • 8
  • 1
    A dictionary is the wrong structure here, you'd be better off with a list of tuples that you can sort and just replace the last entry – Sayse Aug 04 '21 at 11:16
  • Or even better, make the list a [heap](https://docs.python.org/3/library/heapq.html). Then it's as simple as pushing the new value onto the heap, then calling `pop` to remove whatever the lowest value is. – CrazyChucky Aug 04 '21 at 11:37

2 Answers2

0

You can try something like this:

highscore = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10}
score = 11
values = list(highscore.values())

# if the player's score is higher than the highest value in the dictionary
# then reconstruct the dictionary with the minimum value removed
if all(score > value for value in values):
    highscore = {k:v for k, v in highscore.items() if v!=min(values)}

print(highscore)

Output:

{'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}
PApostol
  • 2,152
  • 2
  • 11
  • 21
0

You can try this:

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}

search = 1
{x: y for x, y in d.items() if y != search}
# Out[22]: {'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}
Andreas
  • 8,694
  • 3
  • 14
  • 38