简体   繁体   中英

Python: For loop stops adding items and values to a dictionary after first iteration

I am playing and learning with python, any way i want to slpit the word in half and calculate the occurence of each letter in the word and insert the score in dictionary the output should be like this:

Word: aaazzbbb dict1: first half of the word

{'a': 3,'z': 1}

the issue is that the adding stops dict2: the second half

{'b': 3,'z': 1}

as it seems to stop adding items to the dictionary after the first iteration with the for loop which is very strange.

below my function and what it gives

def pal2(word):
    wordLength = len(word)
    word1 = ""
    word2 = ""
    midstr = ""
    dict1 = []
    dict2 = []
    if (wordLength % 2 == 0 ):
        for i in range(int((len(word)/2)-1),-1,-1):
            word1 += word[i]

            if (word[i] not in dict1):
                dict1 = {word[i]:word.count(word[i],0,int((len(word)/2)-1))}
        for j in range(int((len(word)/2)),len(word),+1):
            word2 += word[j]

            if (word[j] not in dict2):
                dict2 = {word[j]:word.count(word[j],int((len(word) / 2) - 1), len(word))}

this is what it gives

{'a': 3}, {'b': 3}

as you can see only the first letters are inserted

You have many problems with your code, I have fixed some of them to make it work:

  1. You initialize dict1 and dict2 like lists , not dicts .
  2. On each for loop iteration you fully override your dict, so you have only one key in the result.
dict1 = {word[i]:word.count(word[i],0,int((len(word)/2)-1))}
  1. You use incorrect indexes in count function. You have to use
word.count(word[i], 0, int((len(word) / 2)))

instead of

word.count(word[i],0,int((len(word)/2)-1))

and

word.count(word[j], int((len(word) / 2)), len(word))

instead of

word.count(word[j],int((len(word) / 2) - 1), len(word))
  1. Variable in function should be lowercase, so I replaced wordLength with word_length . You have to stick to those standards to increase code readability.
  2. Fixed some other code style issues.
def pal2(word):
    word_length = len(word)
    word1 = ""
    word2 = ""
    dict1 = {}
    dict2 = {}
    if word_length % 2 == 0:
        for i in range(int((len(word) / 2) - 1), -1, -1):
            word1 += word[i]
            if word[i] not in dict1:
                dict1[word[i]] = word.count(word[i], 0, int((len(word) / 2)))
        for j in range(int((len(word) / 2)), len(word), 1):
            word2 += word[j]
            if word[j] not in dict2:
                dict2[word[j]] = word.count(word[j], int((len(word) / 2)), len(word))
    print(dict1)
    print(dict2)


pal2("aaazzbbb")

Output:

{'z': 1, 'a': 3}
{'z': 1, 'b': 3}

Instead of creating a dictionary each time, you need to update your initial dictionary.

To explain, first you have to create an empty dictionary:

dict1 = {}

Then, we replace this code, where you are creating a completely new dictionary:

dict1 = {word[i]:word.count(word[i],0,int((len(word)/2)-1))}

By this (update original dictionary, to include existing elements):

dict1.update({word[i]:word.count(word[i],0,int((len(word)/2)))})

Check the update method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM