否定更新Python字典[NOT"key"]

pat*_*ick 4 python dictionary

我正在寻找一种通过寻址与给定键不匹配的所有键来更新/访问Python字典的方法.

也就是说dict[key],我想做的事情不是通常的dict[!key].我发现了一种解决方法,但我认为必须有一种更好的方法,我现在无法弄清楚.

# 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"})
Run Code Online (Sandbox Code Playgroud)

Jea*_*bre 5

dicti.update({k: v + 1 for k,v in dicti.items() if k != "male"})
Run Code Online (Sandbox Code Playgroud)

创建一个子字典(散列,内存开销),然后将其传递给旧字典:更多散列/ ref复制.

为什么密钥上没有一个好的旧循环(因为值不可变):

for k in dicti:
   if k != "male":
       dicti[k] += 1
Run Code Online (Sandbox Code Playgroud)

如果有很多键并且只有一个键可以避免,可能会更快:添加到所有键,并取消对要避免的一个键的操作(节省了大量的字符串比较):

for k in dicti:
   dicti[k] += 1
dicti["male"] -= 1
Run Code Online (Sandbox Code Playgroud)

如果值是可变的(例如:列表),我们将避免一次散列并改变该值:

for k,v in dicti.items():
   if k != "male":
       v.append("something")
Run Code Online (Sandbox Code Playgroud)

单行很酷,但有时最好避免它们(在这种情况下的性能和可读性)