Adding a constant integer to a value in a python dictionary

前端 未结 3 1899
陌清茗
陌清茗 2021-01-15 17:55

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          


        
3条回答
  •  时光取名叫无心
    2021-01-15 18:22

    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)
    

提交回复
热议问题