How can I modify or replace each value in a dictionary in the same way?

Question:

Given a dictionary like myDict = {'ten': 10, 'fourteen': 14, 'six': 6}, how can I modify each of the values? For example, I’d like to divide each value by two, so that myDict becomes {'ten': 5, 'fourteen': 7, 'six': 3} (in place, not creating a new dictionary).

Asked By: tkbx

||

Answers:

To iterate over keys and values:

for key, value in myDict.items():
    myDict[key] = value / 2

The default loop over a dictionary iterates over its keys, like

for key in myDict:
    myDict[key] /= 2

or you could use a map or a comprehension.

map:

myDict = map(lambda item: (item[0], item[1] / 2), myDict)

comprehension:

myDict = { k: v / 2 for k, v in myDict.items() }
Answered By: bokonic

Using the dict.items() method and a dict comprehension:

dic = {'ten': 10, 'fourteen': 14, 'six': 6}
print({k: v/2 for k, v in dic.items()})

Output:

{'ten': 5.0, 'six': 3.0, 'fourteen': 7.0}
Answered By: aldeb

Python 3:

>>> my_dict = {'ten': 10, 'fourteen': 14, 'six': 6}
>>> for key, value in my_dict.items():
       my_dict[key] = value / 2
>>> my_dict
{'fourteen': 7.0, 'six': 3.0, 'ten': 5.0}

This changes the original dictionary. Use // instead of / to get floor division.

Answered By: Mike Müller

Iterate over keys, and use them to access, modify and assign back the corresponding values. For example:

for k in myDict:
    myDict[k] /= 2
Answered By: Elazar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.