0

question answerers and python wizards,

I am a weary apprentice seeking some help from a fellow traveller.

inventory = {
'gold' : [500, 600, 700, 800],
'pouch' : ['flint', 'twine', 'gemstone'],
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}

I essentially want to iterate through the 'gold' key and add 50 to each value and have that stored [permanently in the original dictionary]. Now, I know how to do it individually...

inventory['gold'][0] += 50
inventory['gold'][1] += 50
inventory['gold'][n] += n...

but, I'm guessing there must be an easier way to do this task?!!!! Right??!

Any help would be appreciated.

Thank y'all in advance!

3
  • inventory['gold'] = [n + 50 for n in inventory['gold']]? Commented Jun 17, 2018 at 23:45
  • inventory['gold'][n] += n Commented Jun 17, 2018 at 23:45
  • Thank you all. Special thanks to @bla - you were totally right! Thanks again, wizards. Commented Jun 17, 2018 at 23:48

1 Answer 1

0

You can use a for loop.

for n in range(len(inventory['gold'])):
    inventory['gold'][n] = inventory['gold'][n] + 50

And in a single line

inventory['gold'] = [n + 50 for n in inventory['gold']]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.