I want to update specific elements of dict with function application in python

Asked 2 years ago, Updated 2 years ago, 27 views

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.

Question

"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)

python

2022-09-30 21:38

1 Answers

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.


2022-09-30 21:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.