Problem with dictionary - Attributeerror: 'int' Object has no attribute 'get'

Asked

Viewed 682 times

1

I’m starting to learn the basics in Python, and one of the examples about dictionary lists asks for something like this:

inventory = {'a' : 1 , 'b' : 6 , 'c' : 42 , 'd' : 1 , 'e' : 12}

def DisplayInventory(stuff):
    for k,v in stuff.items():
        stuff = k + v.get(stuff,0)
        print(k+v)

DisplayInventory(inventory)

Only I keep making that mistake:

Traceback (most recent call last):
   line 8, in <module>
    DisplayInventory(a)
   line 5, in DisplayInventory
    stuff = k + v.get(stuff,0)
AttributeError: 'int' object has no attribute 'get'    
  • in each iteration, k will be a key (first it will be a, then b, then c etc.) and v will be the number corresponding to that key in the dictionary (1, 6, 42 etc.). It makes no sense to "get" a number. Neither I nor Python are understanding what you wanted to do there, so the mistake. Explain what exit you want because you are probably on the wrong track. Do the [tour] and read on [Ask] to know how to ask questions that are easier to answer.

  • The intention of the exercise I tried to do is to display with print something like the key name plus the value name of that key

  • What do you want to do in this line "Stuff = k + v.get(Stuff,0)" ?

1 answer

1

The error happened because you tried to call a method that does not exist in int.

v.get(stuff,0)

As you explained later in the comments you just wanted to show the key and value of each element in inventory, I managed to reach the following code from your:

inventory = {'a' : 1 , 'b' : 6 , 'c' : 42 , 'd' : 1 , 'e' : 12}

def DisplayInventory(stuff):
    for k,v in stuff.items():
        print(str(k) + ' ' + str(v))

DisplayInventory(inventory)

Browser other questions tagged

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