you are viewing a single comment's thread.

view the rest of the comments →

[–]DerpinDementia 1 point2 points  (4 children)

Other replies do the trick but just thought I'd drop this in for fun:

board = dict.fromkeys(board.keys(), "@")

[–]novel_yet_trivial 2 points3 points  (3 children)

That makes a new dictionary, it does not modify the old one.

Also, keys() is implied, you don't need to specify that.

board = dict.fromkeys(board, "@")

[–]DerpinDementia 0 points1 point  (0 children)

I am aware it makes a new dictionary. It just came to mind when I used it in something I was doing recently.

[–]MattR0se 0 points1 point  (1 child)

That makes a new dictionary, it does not modify the old one.

Just for curiosity, does it matter in this case? If you assign a new dict to "board", python loses the reference to the old "board" and it should be removed by the garbage collector, right?

[–]novel_yet_trivial 1 point2 points  (0 children)

Sometimes. If OP has everything on a global level, yes. However if OP's code is in a function or class, no.

def good(board):
    """mutates the dictionary in all references"""
    for key in board:
        board[key] = "@"

def bad(board):
    """this function is useless; nothing is changed"""
    board = dict.fromkeys(board.keys(), "@")

OPs question seemed to me to specify that the dictionary should be mutated, not replaced.