Modifying List, Adding values to a single key in a Dictionary


#1

Say this is a dic
inventory = {
'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'],
'pocket' : ['seashell','strange berry','lint']
}

Now suppose I want to make the key for 'gold' a list.. i.e may be I want to add 2 more keys like '600' & '700'
I tried a few ways like append() , adding the key to the index value but nothing worked.
Is it possible? If yes what is the way and if not why?


#2

Okay, so first things first. If you want to make gold a list you need to add brackets to the key's value. So, "gold": 500 becomes "gold":[500]. Now that we have established the value of the key "gold" is a list we can append it. When you append it with 600 and 700 make sure you do one at a time because append can only have one input. It will look like this in total.

inventory = {
'gold': [500],
'pouch':['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack':['xylophone','dagger', 'bedroll','bread loaf'],
'pocket':['seashell','strange berry','lint']
}

inventory["gold"].append(600)
inventory["gold"].append(700)
print inventory["gold"]

I hope this helps.


#3

Hi gangware72 , thanks a lot for the reply. Now tell me a thing, suppose I want to add 50 to the key 500 i.e. make it 550 instead of 500. Now suppose I want to add 50 to the key 500 i.e. 550.
So what I found out is like if I do inventory["gold"][0] + 50 its fine.. So is there any other way of doing this or this is only way..?


#4

What your refering to as the key is actually the value. Syntax for dictionaries is {key:value, key:value, key:value} etc. The only way I can think to change the value of your gold key is to modify it like you did and reassaign the value. ie. inventory["gold"][0] = inventory["gold"][0] + 50. Hope that helps deb.


#5

Thanks a lot. My mistake.. I mistook the value for key.. Thanks again :smile: