Negatively update Python dict [NOT "key"]

I am looking for a way to update / access the Python dictionary by accessing all keys that DO NOT match the specified key.

That is, instead of the usual, dict[key]I want to do something like dict[!key]. I found a workaround, but realized that there should be a better way that I cannot understand at the moment.

# I have a dictionary of counts
dicti = {"male": 1, "female": 200, "other": 0}

# Problem: I encounter a record (cannot reproduce here) that 
# requires me to add 1 to every key in dicti that is NOT "male", 
# i.e. dicti["female"], and  dicti["other"], 
# and other keys I might add later

# Here is what I am doing and I don't like it
dicti.update({k: v + 1 for k,v in dicti.items() if k != "male"})
+4
source share
2 answers

If you need to perform this โ€œadd to othersโ€ operation more often, and if all the values โ€‹โ€‹are numeric, you can also subtract from the given key and add the same value to some global variable that counts all the values โ€‹โ€‹(including the same key) . For example, as a wrapper class:

import collections
class Wrapper:
    def __init__(self, **values):
        self.d = collections.Counter(values)
        self.n = 0
    def add(self, key, value):
        self.d[key] += value
    def add_others(self, key, value):
        self.d[key] -= value
        self.n += value
    def get(self, key):
        return self.d[key] + self.n
    def to_dict(self):
        if self.n != 0:  # recompute dict and reset global offset
            self.d = {k: v + self.n for k, v in self.d.items()}
            self.n = 0
        return self.d

Example:

>>> dicti = Wrapper(**{"male": 1, "female": 200, "other": 0})
>>> dicti.add("male", 2)
>>> dicti.add_others("male", 5)
>>> dicti.get("male")
3
>>> dicti.to_dict()
{'other': 5, 'female': 205, 'male': 3}

, add add_others - O (1), , , . , to_dict - O (n), dict , add_other .

+3
dicti.update({k: v + 1 for k,v in dicti.items() if k != "male"})

(, ), : /ref copy.

( ):

for k in dicti:
   if k != "male":
       dicti[k] += 1

, , , : , ( ):

for k in dicti:
   dicti[k] += 1
dicti["male"] -= 1

(ex: lists), :

for k,v in dicti.items():
   if k != "male":
       v.append("something")

, ( )

+5

Source: https://habr.com/ru/post/1694874/


All Articles