Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - select the other element in a dictionary

I'm a beginner in python, and I have a dictionary:

players = {"player 1":0, "player 2":0}

And in this code, I will describe what I want to achieve:

def play_ghost():
    for p_id in cycle(players):
        ##code..
        if end_game() : ##if this is true, add 1 to the OTHER player
            ##what to write here ?

Sorry if my question is kinda obvious but I really don't want to achieve this using if statements and such. I'm looking for a single method or something that can select the other element (like in JavaScript where I can select sibling).

like image 429
Rafael Adel Avatar asked Sep 10 '26 20:09

Rafael Adel


1 Answers

Try this:

wins = {"player1": 0, "player2": 0}
this, other = "player1", "player2"
for i in range(rounds_count): # really, variable i don't use
    this, other = other, this # swap players
    if end_game():
        wins[this] +=1
    else:
        wins[other] += 1  
like image 200
timakina Avatar answered Sep 12 '26 10:09

timakina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!