How do you update all the items in a dictionary at once?

Viewed 97

So I have a dictionary, and I want to update all the values in the dictionary with a for loop. I assume it would go something like this:

fruits = {"apple" : 2, "banana" : 1, "orange" : 4}

for value in fruits:
  value += 2

print(fruits)

I expect it to print {"apple" : 4, "banana" : 3, "orange" : 6}, but instead it just prints the original list. I am not quite sure how to fix this, so any insight would be greatly appreciated.

4 Answers

Do this:

fruits = {"apple" : 2, "banana" : 1, "orange" : 4}

for key in fruits:
  fruits[key] += 2

print(fruits) # {"apple" : 4, "banana" : 3, "orange" : 6}

You can try this:

for i in fruits.keys():
    fruits[i] = fruits[i]+2

If you like one-liners:

fruits = {x: fruits[x]+2 for x in fruits}

or use update

fruits.update((x,fruits[x]+2) for x in fruits)

The only way to do this is to iterate through each of them.

fruits = {"apple" : 2, "banana" : 1, "orange" : 4}
fruits = {k:v+2 for k,v in fruits.items()}
print (fruits)

The output:

Before:

{'apple': 2, 'banana': 1, 'orange': 4}

After:

{'apple': 4, 'banana': 3, 'orange': 6}
Related