Tyler Seymour
Tyler Seymour

Reputation: 617

iterating over a string in a list in a dictionary PYTHON

I've got a dictionary full of lists called "possible" with keys 'a' - 'z'. Each key has the value of a list with 'a' through 'z' in it. Essentially, 26 alphabets.

I clean a string into lowercase and strip the punctuation and save each word into a list named "cleanedWords".

I want to go through the list and if the word in the list has only two letters, remove the value 'c' from the key for both of the letters in the two letter word. Then move on the the next 2 letter word and repeat.

This is the snippet with the error:

for y in cleanedWords:
    if len(y) == 2:
        for i in y:
            possible[i].remove('c')

Here is the error:

Traceback (most recent call last):
  File "F:\python\crypto\cipher.py", line 83, in <module>
    possible[i].remove('c')
ValueError: list.remove(x): x not in list

Clearly I am doing something wrong. Can someone point me in the right direction? Can I not call on "y" how I did?

Tyler

Upvotes: 2

Views: 182

Answers (2)

Tyler Seymour
Tyler Seymour

Reputation: 617

for y in cleanedWords:
    if len(y) == 2:
        print y
        for i in y:
            try:
                possible[i].remove('c')
            except ValueError:
                pass

Upvotes: 0

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

Ok, i am not familiar with your(share it if you want the detailed answer) data structure, but it looks for me that you need to replace your code with:

for word in (x for x in cleanedWords if len(x) == 2):
    for ch in word:
        if 'c' in possible[i]:
            possible[ch].remove('c')

Upvotes: 1

Related Questions