how can i add to into dictionarys value?

Question:

i want to add 1 each time a word repeats:

def grocery():
    try:
        items = {}
        while True:
            prompt = input('')
            for i in prompt.split():
                items.update({i:1})
            for key, value in items.items():
                if i == key:
                    items[key] += 1
    except EOFError:
        print(items)
        pass

grocery()

but it adds 1 to all keys, when my input is : apple apple banana, it should be {‘apple’:2,’banana’,1}
but it is {‘apple’:2,’banana’,2}

Asked By: Peiman Esmaeili

||

Answers:

Here’s an example that uses a dictionary’s get() function.

def grocery():
    items = {}
    while (groceries := input('Enter a single item or several items separated by whitespace (Return to quit): ')):
        for item in groceries.split():
            items[item] = items.get(item, 0) + 1
    return items

print(grocery())

Input:

Enter a single item or several items separated by whitespace (Return to quit): apple
Enter a single item or several items separated by whitespace (Return to quit): banana
Enter a single item or several items separated by whitespace (Return to quit): orange apple
Enter a single item or several items separated by whitespace (Return to quit):

Output:

{'apple': 2, 'banana': 1, 'orange': 1}

Note:

You will need to use Python 3.8 or later in order for the walrus operator (:=) to work.

Answered By: Stuart
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.