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


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?


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']

print inventory["gold"]

I hope this helps.


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..?


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.


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