How would you add a constant number, say 1, to a value in a dictionary if certain conditions are fulfilled.
For example, if I had a dictionary:
dict
Another way of doing this would be to use the items() method of dictionary which returns a list of key, value tuples:
def f(dict):
for entry in dict.items():
if entry[1] > 1 and entry[1] < 5:
dict[entry[0]] = entry[1] + 1
return dict
You can then extend this to take an arbitrary function:
def f(dict, func):
for entry in dict.items():
if func(entry[1]):
dict[entry[0]] = entry[1] + 1
return dict
This can be provided a function such as:
def is_greater_than_one(x):
return x > 1
and called in the following way:
f(input_dictionary,is_greater_than_one)