Michael
Michael

Reputation: 101

Is there a shorthand for using the same variable being assigned for the argument in a function?

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

Answers (3)

Steven Moseley
Steven Moseley

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

John Y
John Y

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

idjaw
idjaw

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:

  • D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
  • If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
  • If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
  • In either case, this is followed by: for k in F: D[k] = F[k]

So, if the key exists, it will update it, and if it does not, it will create it.

Upvotes: 1

Related Questions