I am stuck on the second problem on Problem Set 4. I'm getting TypeError saying list indices must be integers, not str whenever I run my code. can Anyone bother to help me debug? def update_hand(hand, word): n = len(word) hand = deal_hand(n) characters = '' for j in hand: count = int(hand.get(j,0)) print hand.keys()[j] characters += hand.keys()[j]*count characters = characters.remove(word) for letter in character: hand[x] = hand.get(x,0)+1 return display_hand(hand)
Sorry it's actually on Problem Set 3.
This is saying you are storing something in a list. Is hand a dict or a list? If hand is a dict then count = int(hand.get(j,0)) should be OK. But if hand is a list, well, then you are tryinging to use a get method on a list.
hand is dict. I am getting an error on the line saying 'print hand.keys()[j]' though. I want to print each key values of hand. Am I misunderstanding some syntax about dictionary?
keys() returns a list from the entire dict. for j in hand sets j to each element of hand for ech process in the loop. print hand.keys()[j] tries to look for the jth element in hand's keys, which makes no sense since j is not an integer.
Check your for loop: for j in hand: what this loop is saying, is that for every item in hand (the dictionary), assign the variable 'j' to each key contained in hand. Then when you try to print hand.keys()[j], the value of j is merely a key contained in hand that it is currently assigned to. When you access hand.keys(), it returns a list of all the keys contained in the dictionary. Remember that you need to use integers for indexing lists. try printing this outside of your loop to see what you get: print hand.keys() If you want to get the key and the value, use this: for key, value in hand.iteritems(): print key, value If you're trying to access the value using the key, then you would do this: for j in hand: print hand[j]
Thank You guys for such feedback :)
Hey, I am also wondering how I can remove a character from string? This is my latest code. n = int(raw_input('# of letters:')) hand = deal_hand(n) print 'hand =',hand characters = '' i = 0 for j in hand: count = int(hand.get(j,0)) print hand.keys()[i] characters += hand.keys()[i]*count print characters i += 1 for ch in word: print 'ch=', ch characters.replace("ch","") print 'left over=', characters for letter in characters: hand[x] = hand.get(x,0)+1 return display_hand(hand) # Can I use str.replace() to remove character since it doesn't seem to work...
I'm not sure if this answer is too late, but you could try string.strip() - google the usage of it.
Join our real-time social learning platform and learn together with your friends!