Now we have dict d
and the function f
that we want to apply as an update to that particular element.Now I would like to do the following for the dict key k
.
d[k]=f(d[k])
This is not a problem if the variable name is so short, but if the variable name gets longer, it will be difficult to do this.
"Is there a way to write ""apply function f to the elements of dict and update"" beautifully?"
As an image, I would like to be able to do the following:
d.replace(f,k)
The dict
type is mutable and can be rewritten directly within a function.You can apply functions as f(d,k)
as shown in the example below.
def value_add_one(dic, key):
dic [ key ] += 1
defmain():
some_dict = {
"Alice": 10,
"Bob": 20,
}
value_add_one(some_dict, "Bob")
print(some_dict)#=> {'Alice':10, 'Bob':21}
if__name__=="__main__":
main()
Incidentally, another type of dict
is the frozendict
type.
© 2025 OneMinuteCode. All rights reserved.