Reputation: 101
Is there a quicker way to write this:
def foo():
# What happens in here is irrelevant.
return new_value
dict['i_dont_want_to_type_this_twice'] = foo(dict['i_dont_want_to_type_this_twice'])
Like when you use x += 1
Upvotes: 0
Views: 94
Reputation: 16345
How about this for a one-liner assignment?
dict.update({key: foo(dict[key]) for key in ['i_dont_want_to_type_this_twice']})
Or, to update the entire dict:
dict = {k: foo(v) for k, v in dict.items()}
Upvotes: 1
Reputation: 14539
I don't think there's any built-in or standard library feature for this. The most idiomatic thing to do is probably define your own wrapper function, such as
def transform(d, k, f):
d[k] = f(d[k])
And then use it like so (note that I've renamed your dict
to mydict
to avoid masking the built-in):
transform(mydict, 'i_dont_want_to_type_this_twice', foo)
(I think apply()
would make a decent name for this, but it's a built-in if you're using Python 2. Though it's been deprecated since 2.3, so there wouldn't be a lot of harm in it.)
Upvotes: 1
Reputation: 26600
You can do something like this, by using update
on the dictionary.
d.update(a=foo(d.get('a', 0)))
Full demo:
d = {'a': 5}
def foo(val):
val += 100
return val
d.update(a=foo(d.get('a', 0)))
print(d) # outputs {'a': 105}
From the description of the dictionary update
method:
So, if the key exists, it will update it, and if it does not, it will create it.
Upvotes: 1