198,286 views
28 votes
28 votes
How does this code give me 17? (python)

j = 3

z = {}

z[2] = 1

z[7] = 3

z[5] = 2

for l in z:

j += l

print(j)


I don't understand where the 17 is coming from. I thought the square brackets were basically accessing the location (meaning the code would be like this "1, 2, 3." I even thought of individually adding 3 separately to all the numbers only for it to give me 15. Yeah, i've trying to understand this for 2 days lol.

User John Ptacek
by
3.0k points

1 Answer

10 votes
10 votes

Answer:

See explanation below and try out this code to see what exactly is happening

# Program

j = 3

z = { ] # empty dictionary

print(z)

z[2] = 1 # z

print(z)

z[7] = 3

print(z)

z[5] = 2

print(z) # prints out {2: 1, 7: 3, 5: 2}

for l in z:

print("Initial value of j = ", j)

print("Value of l(key) = ", l)

j += l

print("Updated value of j = ", j)

print("Final value of j=", j)

Step-by-step explanation:

What you have is a dictionary object. We use { } to represent a dictionary. A dictionary consists of keys and values related to the keys. For example, you can have a dictionary which contains names of students and their GPAs

This is declared as
student_grades = {"Amy": 4.3, "Zach":4.0", "Bill": 3.2}

The names are referred to as keys and the GPA as values
You can also have both key and value as integers. Fir example you could store the cubes of numbers from 1 to 5 in a dictionary

cubes = {1: 1, 2:8, 3: 27, 4: 64, 5:125}

If you wanted to add the cube for 6 then you would use cubes[6] = 216 This creates a new entry in the dictionary 6:216 so that the dictionary is now

cubes = {1: 1, 2:8, 3: 27, 4: 64, 5:125, 6:216}

In this short program here is what is happening


j = 3 # variable j created and value set to 3

z = { } # this creates an empty dictionary named z

z[2] = 1 #adds an entry with key = 2 and value = 1; z = {2 : 1}

z[7} = 3 #key 7 and value 2 added => z = {2 : 1, 7 : 3}

z[5] = 2 #key 5, value 2 => z = {2: 1, 7 : 3, 5 : 2}

So now there are 3 entries in the dictionary i.e. 3 pairs of key-values

When you iterate through the dictionary as in

for l in z:
- you are actually iterating over the keys so l = 2, 7 and 5 on each iteration

So you are accumulating the key values

Here is what happens

First execution of loop => j = 3 , l = 2 (first key =2), j = 3 + 2 = 5

Second time: l = 7 (second key value) , j = 5 + 7 = 12

Third time: l = 5, j = 12 + 5 = 17

There is a lot more to dictionaries and sometimes it can get complicated. Suggest you search the internet for the same

Putting print() statements also helps you visualize what is happening. Code is provided in the answer section to help you

User AlexisBRENON
by
2.8k points