CutePoison
CutePoison

Reputation: 5365

Update multiple key/value pairs in python at once

Say I have

d =  {"a":0,"b":0,"c":0}

is there a way to update the keys a and b at the same time, instead of looping over them, such like

update_keys = ["a","b"]
d.some_function(update_keys) +=[10,5]

print(d)
{"a":10,"b":5,"c":0}

Upvotes: 1

Views: 1557

Answers (4)

riskRewarded
riskRewarded

Reputation: 99

If you are just storing integer values, then you can use the Counter class provided by the python module "collections":

from collections import Counter

d =  Counter({"a":0,"b":0,"c":0})

result = d + Counter({"a":10, "b":5})

'result' will have the value of

Counter({'a': 10, 'b': 5})

And since Counter is subclassed from Dict, you have probably do not have to change anything else in your code.

>>> isinstance(result, dict)
True

You do not see the 'c' key in the result because 0-values are not stored in a Counter instance, which saves space.

You can check out more about the Counter instance here.

Storing other numeric types is supported, with some conditions:

"For in-place operations such as c[key] += 1, the value type need only support addition and subtraction. So fractions, floats, and decimals would work and negative values are supported. The same is also true for update() and subtract() which allow negative and zero values for both inputs and outputs."

Performing the inverse operation of "+" requires using the method "subtract", which is a note-worthy "gotcha".


>>> d = Counter({"a":10, "b":15})
>>> result.subtract(d)
>>> c
Counter({'a': 0, 'b': 0})

Upvotes: 0

whilrun
whilrun

Reputation: 1724

If you mean a function that can add a new value to the existing value without an explict loop, you can definitely do it like this.

add_value = lambda d,k,v: d.update(zip(k,list(map(lambda _k,_v:d[_k]+_v,k,v)))) or d

and you can use it like this

>>> d = {"a":2,"b":3}
>>> add_value(d,["a","b"],[2,-3])
{'a': 4, 'b': 0}

There is nothing tricky here, I just replace the loop with a map and a lambda to do the update job and use list to wrap them up so Python will immediately evaluate the result of map. Then I use zip to create an updated key-value pair and use dict's update method the update the dictionary. However I really doubt if this has any practical usage since this is definitely more complex than a for loop and introduces extra complexity to the code.

Upvotes: 1

Gamopo
Gamopo

Reputation: 1598

Yes, you can use update like this:

d.update({'a':10, 'b':5})

Thus, your code would look this way:

d =  {"a":0,"b":0,"c":0}
d.update({'a':10, 'b':5})
print(d)

and shows:

{"a":10,"b":5,"c":0}

Upvotes: 2

66dibo
66dibo

Reputation: 19

Update values of multiple keys in dictionary

d =  {"a":0,"b":0,"c":0}

d.update({'a': 40, 'b': 41, 'c': 89})

print(d)

{'a': 40, 'b': 41, 'c': 89}

Upvotes: 0

Related Questions