Reputation: 690
I have the following dictionary:
players = {'Roger': ['player1', 'dA'], 'Luka': ['player2', 'sK']}.
I want to update the key that contains 'player2'
, but
I can't update players[Luka]
because 'player2'
is not always Luka
. How can I select keys linked to 'player2'
?
(for those wondering, dA = Ace of Diamonds
, sK = King of Spades
. These values will also be different every time).
Edit: Here's the part of my code: (It won't run because I left out a lot of clutter)
qPlayers = 2 #Amount of players
def game(qPlayers):
players[nr]["value"].append(new_card)
deal_to =[]
for player in players:
deal_to.append(player)
deal(qPlayers,deck,players,deal_to)
def setup(qPlayers):
playerhands = []
for x in range(1,qPlayers+1):
player = {}
player["name"] = input("Enter your name, player {}\n>>>".format(x))
playerhands.append(player)
return playerhands
def deal(qPlayers,deck,players,deal_to):
nr = -1
for player in deal_to:
nr +=1
new_card = getCard(deck) #getCard produces a random card like sA, k9, cQ
Upvotes: 0
Views: 102
Reputation: 339200
You can iterate the dictionary to find the key to update. dict.iteritems()
will do that job in python 2.7.
players = {'Roger': ['player1', 'dA'], 'Luka': ['player2', 'sK']}
for key, value in players.iteritems():
if value[0] == "player2":
players[key][1] = "sQ"
print players
Upvotes: 1
Reputation: 18233
You have two options here:
Search through the entire directory, checking for the value which contains 'player2'. This ends up being inefficient, and makes the dictionary structure somewhat useless.
Use a list instead of a dictionary, and model your data accordingly, similar to the example below.
An advantage of this data structure is that you don't need the redundant player1
/player2
identifiers, since the list index provides that implicitly. To reference player2
you'd take the second element from the list (players[1]
since indexing starts at 0).
players = [
{'Name' : 'Roger', 'Value' : 'dA'},
{'Name' : 'Luka', 'Value' : 'sK'}
]
Upvotes: 1
Reputation: 336
You can keep track of which key
in the dict
contains your player2
value, or else you will have to iterate through the dict
until you find a key
that does. If you frequently need to search based on something internal to the value
, you may want to reconsider the data structure you are using to store this data.
def findKeyWithValue(value):
for playerName, playerData in players.items():
if value in playerData:
# your code here
Upvotes: 2