It’s Dangerous to Go Alone! Take This( alternate problem)


#1



Have solved this excercise, but one doubt is there, if for instance the problem was to insert 50 in "Gold" besides 500 ie.- 'gold': 500,50 .how we should have approached it. i tried using inventory['gold'].append(50) but it shows error.also if we want to add certain string in the 'backpack' at specific place say1/2/3etc, how we should approach. because inventory['backpack'][4]='new item' also gives error. kindly explain.


#2

well, if you have two numbers and you need to add the numbers together/get the sum, what math operator would you use? i would use +, its basic math

.append() is a method to add/append to a list, 500 is a integer, not a list

python has a built in function for this, its called insert(), the first argument should be the index and the second argument the value you want to insert at this index


#3

sir for the first part of my question am telling if we want to insert two values in gold like this
'Gold': 500, 50 , am not saying 'Gold': 550(not asking to add 50) .kindly explain how to insert other value in it

And for second part got it, now will use insert with two arguments as you have told.


#4

well, what data type we have which can hold multiply values and are mutable? lists, so we would need to give the gold key a list value, the list should contain 500


#5

sir so we cant do it without list?that means in dictonary we can give only single value with data if we are not using list inside it.


#6

well, if you want the gold to have multiply values, you will need a list:

inventory = {
      'gold': [500],
      # rest of dictionary
}

inventory['gold'].append(50)

An integer can only be a single value, both inside and outside a dictionary.


#7

thanks sir , for your explanation.:slightly_smiling_face:


#8

I found out that it is not intended to add an element '50' to gold as a second value, but to simply add it to 500:
inventory['gold'] = inventory['gold'] + 50 (worked)


#9

but this question was never about how to complete the exercise


#10

Thanks. This is what I've been looking for.


#11