Gives Out Key Error = 0 When Using Insertion Sort In Python
in my lottery game i need to create 1000 players and each player has a number set which needs to be compared with a winning number set. all the numbers sets are from a barrel of 0-
Solution 1:
You are iterating over the dictionary with the wrong key.
Here the right code:
forkeyin players:
print(players[key])
For mappings (like dictionaries), .__iter__()
should iterate over the keys. This means that if you put a dictionary directly into a for loop, Python will automatically call .__iter__()
on that dictionary, and you’ll get an iterator over its keys.
Solution 2:
Note: I have not reviewed your sorting algorithm for correctness. This answer solely addresses the KeyError.
KeyError is raised because you are trying to look for a key in a dict that isn't there.
defgenerateID():
...
for player_id inrange(1, 1001): # Populates player IDs from 1, 2, 3...
players[player_id] = ...
for i inrange(len(players)): # Searches player IDs from 0, 1, 2...print (players[i])
In general, just loop over players. Since it is a dictionary, you can use .items()
to retrieve the keys and values:
defgenerateID():
...
forid, player_list in players.items():
print (player_list)
Post a Comment for "Gives Out Key Error = 0 When Using Insertion Sort In Python"