Python scrabble project

Hi, I am doing this exercise. I have a dictionary with names of players as the keys, and lists of words as the values. I am trying to create a function to add words to the players’ lists. I tried this code

#Dictionary of scrabble players and their words
players_words = {'alex':['BLUE', 'TENNIS'  'EXIT'], 'david':['EARTH', 'EYES', 'MACHINE'], 'john':['ERASER', 'BELLY', 'HUSKY'], 'jane': ['ZAP', 'COMA', 'PERIOD']}

#Define function to add a word for a player
def play_word(player, word):
  players_words[player] += word

play_word('alex', 'WORK')

print(players_words)

The result I get is this:
{‘alex’: [‘BLUE’, ‘TENNISEXIT’, ‘W’, ‘O’, ‘R’, ‘K’], ‘david’: [‘EARTH’, ‘EYES’, ‘MACHINE’], ‘john’: [‘ERASER’, ‘BELLY’, ‘HUSKY’], ‘jane’: [‘ZAP’, ‘COMA’, ‘PERIOD’]}

Why does it split up the letters to separate entries in the list, and what code will add the new word to the list?

Thanks!

Using += to mutate a list is generally equivalent to using the .extend() method. This method takes some form of iterable sequence as an argument and appends each element of this sequence to the list- 5. Data Structures — Python 3.9.1 documentation. In your case it’s iterating through your string and consequently splitting the string into individual characters and appending each one. If it’s a single element you want to add to the list then .append would be what you’re looking for.

1 Like