Problem with Python Dictionaries

Asked

Viewed 34 times

-3

def main():
    insereDic()
def insereDic():
    frase = input('>>>')
    for i in frase:
        if i in dic:
            dic[i] =+ 1
        else:
            dic[i] = 1
    print(dic)
dic = {}
main()

Statement of the Year

https://i.stack.Imgur.com/cDShb.png

The output in the terminal with the input "algorithms and programming" is: {'a': 1, 'l': 1, 'g': 1, 'o': 1, 'r': 1, 'i': 1, ’t': 1, ’m': 1, 's': 1, ' ': 1, 'e': 1, 'p': 1, 'c': 1}

Instead of: {'a': 4, 'l': 1, 'g': 2, 'o': 4, 'r': 3, 'i': 1, ’t': 1, ’m': 2, ’s': 1, ' ': 2, 'e': 1, 'p': 1, 'c': 1} (that would be the correct exercise)

1 answer

1

Bryan, the problem is only at the moment of incrementing the value of the already existing key, the correct is +=:

def main():
    insereDic()

def insereDic():
    frase = input('>>>')

    for i in frase:
        if i in dic:
            dic[i] += 1
        else:
            dic[i] = 1
    print(dic)

dic = {}
main()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.