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).
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() }
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}
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.
Iterate over keys, and use them to access, modify and assign back the corresponding values. For example:
for k in myDict:
myDict[k] /= 2
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).
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() }
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}
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.
Iterate over keys, and use them to access, modify and assign back the corresponding values. For example:
for k in myDict:
myDict[k] /= 2