How do I fix the NameError in my python lottery

51 Views Asked by At

I am making a dictionary and I set up a variable string thing inside the dictionary and it's "numbers" and when I tried to pull the information it gave me a NameError saying it wasn't defined and I'm too stupid to figure it out.

x = {"player_1":"Player 1", "numbers":{2,5,4,43,12,24}}
x_1 = {"player_2":"Player 2", "numbers":{12,14,23,35,15,6}}
x_2 = {"player_3":"Player 3", "numbers":{32,2,65,35,32}}
x_3= {"player_4":"Player 4", "numbers":{24,23,26,58,27}}

for playername in x:
    inter_var = len(this_dict[numbers].intersection(playername))
    top_player = playername
 
    if inter_var > len(top_player[numbers].intersection(lottery_numbers)):
        print(f"{top_player} won {winnings}")
2

There are 2 best solutions below

0
Mark Tolonen On

Not sure what your goal is, but you should start with something like the following, with consistent keys and a goal like counting matching numbers:

players = [{'name': 'Player 1', 'numbers': { 2,  5,  4, 43, 12, 24}},
           {'name': 'Player 2', 'numbers': {12, 14, 23, 35, 15,  6}},
           {'name': 'Player 3', 'numbers': {31,  2, 65, 35, 32, 12}},
           {'name': 'Player 4', 'numbers': {24, 23, 26, 58, 27,  7}}]

lottery_numbers = { 2, 5, 4, 43, 12, 1}

for player in players:
    count = len(player['numbers'].intersection(lottery_numbers))
    print(f"{player['name']} matched {count} numbers.")

Output:

Player 1 matched 5 numbers.
Player 2 matched 1 numbers.
Player 3 matched 2 numbers.
Player 4 matched 0 numbers.
0
Naitzirch On

You're already iterating over the list of dictionaries using your for-loop. In your for-loop, playername is each dictionary, so you could just write

playername["numbers"]

if you want to access the numbers for each player.

As a sidenote, it looks like you're taking the intersection between the set of numbers and the dictionary, which I don't think is a desired behaviour (this will always result in the empty set).