I'm new to coding and am trying to get the sum of these 'y' values, but nothing I've tried seemed to work

37 views Asked by At

So I'm trying to sum up the 'y' values of this code, so I can use it later on. Everything I've tried so far (a lot) didn't seem to work. And I just don't know how to fix it. This is my code:

inventory = {
'x' : {'x': 1, 'y': 2, 'z': 3},
'y' : {'x': 4, 'y': 5, 'z': 6}}

for key in inventory:
  print(sum(inventory[key]['y']))

And this is the error code I get:

Traceback (most recent call last):
  File "/home/runner/School-project/main.py", line 6, in <module>
    print(sum(inventory[key]['y']))
TypeError: 'int' object is not iterable

I tried many things, which I don't even remember at this point to be honest. But if somebody could help it would be great!

2

There are 2 answers

1
CDubyuh On

You were super close!

inventory = {
'x': {'x': 1, 'y': 2, 'z': 3},
'y': {'x': 4, 'y': 5, 'z': 6}
}

sum = 0
for key in inventory:
    sum += inventory[key]['y']

print(sum)

You were never actually adding any values together, but you had the right idea. The sum() function expects an iterable like a list, and you were trying to use it with a raw integer.

This line:

inventory[key]['y']

Returns the each value with the 'y' key, and the values you have are integers.

0
Reilas On

Here is the Python tutorial, on dictionaries.
Python 3.12.0 documentation — The Python Tutorial — 5. Data Structures.

This is similar to @CDubyuh's answer.

a = 0
for k, v in inventory.items():
    if 'y' in v: a += v['y']

Output

7