0

I am having trouble accessing the list value inside my dictionary. I want to find the list of the player's results using their name, which is my key. when I try to run this nothing happens. I believe there's an error in the logic.

x=int(input())
search_player=input()
if 2<=x<=10:
    player_results={}
    for i in range(x):
        player,*pol=input().split()
        scores=list(map(float,pol))[:3]
        player_results[player]=scores
    for key,value in player_results.items():
        if key==search_player:
            print(value)
not_speshal
  • 22,093
  • 2
  • 15
  • 30
  • 2
    Can you explain what do you want to do? –  Jul 19 '21 at 16:25
  • I would recommend changing the variable `x` to something that specifies its use a bit more. See [What are “symbolic constants” and “magic constants”?](https://stackoverflow.com/a/43951017/5763413) – blackbrandt Jul 19 '21 at 16:27
  • I want to get the list of any player's scores by searching their usernames. – Lungile Ngidi Jul 19 '21 at 16:28

1 Answers1

2

You can simply get the value of a dictionary d for a particular key using d[key] or, even better, d.get(key) which allows you to specify a default value if the key doesn't exist in the dictionary. You don't need to iterate over the dictionary.

Try this instead:

x = int(input("Enter the number of players: "))
search_player = input("Enter the player to search for: ")

if 2<=x<=10:
    player_results={}
    for i in range(x):
        player, *pol = input(f"Enter name and scores for player {i}:\n").split()
        scores = list(map(float,pol))[:3]
        player_results[player] = scores
    
    print(player_results.get(search_player, "Invalid player name"))
not_speshal
  • 22,093
  • 2
  • 15
  • 30