why does the dictionary key not update to record the change in keys

Question:

the goal is to increase the dictionary key by 1 so all values generated by for loop are stored in a dictionary

code

counting = {}
numbers = 1


for i in range(1, 11):
    counting[numbers] = (i)
    numbers + 1

print(counting)

but in the final result the dictionary only has one key and one stored value that is

result of running the code
{1: 10}

how do i make it that the keys changes with each loop and stores all the values generated

but in the final result the dictionary only has one key and one stored value that is

result of running the code
{1: 10}

how do i make it that the keys changes with each loop and stores all the values generated

Asked By: noob

||

Answers:

You have to put numbers += 1 or numbers = numbers + 1 instead of numbers + 1 if you want to update the variable.

When python sees numbers + 1, it just evaluates that line, gets 2, and does nothing with that value. If you don’t have an = sign, the variable will not be changed.

Answered By: siIverfish

I don’t think you realize, but there’s a silly typo in your code. After assigning the value to dictionary, you increasing the count of numbers, but not assigning it. So, just use += assignment operator.

counting = {}
numbers = 1


for i in range(1, 11):
    counting[numbers] = (i)
    numbers += 1

print(counting)

O/P:

{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}
Answered By: 8D Masters
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.