Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negatively updating a Python dict [NOT "key"]

I am looking for a way to update/access a Python dictionary by addressing all keys that do NOT match the key given.

That is, instead of the usual dict[key], I want to do something like dict[!key]. I found a workaround, but figured there must be a better way which I cannot figure out 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"})
like image 297
patrick Avatar asked Jan 29 '23 12:01

patrick


1 Answers

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

that creates a sub-dictionary (hashing, memory overhead) then passes it to the old dictionary: more hashing/ref copy.

Why not a good old loop on the keys (since the values aren't mutable):

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

Maybe faster if there are a lot of keys and only one key to avoid: add to all the keys, and cancel the operation on the one key you want to avoid (saves a lot of string comparing):

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

if the values were mutable (ex: lists) we would avoid one hashing and mutate the value instead:

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

One-liners are cool, but sometimes it's better to avoid them (performance & readability in that case)

like image 129
Jean-François Fabre Avatar answered Feb 15 '23 16:02

Jean-François Fabre