0

Sometimes I cannot use a lambda function on an object because the last method applied to the object returns None. What is the trick to be able to return the object itself instead of the method returned value?

Example, I want to get the updated copy of the dictionary instead of None:

dict_update = lambda d, upd: d.copy().update(upd)

d = dict(lw=3, ls='-')
upd = dict(c='C0', lw=4)
d1 = dict_update(d, upd)
for v in [d, upd, d1]: print(v)

{'lw': 3, 'ls': '-'}
{'c': 'C0', 'lw': 4}
None
4
  • 4
    The trick is to not use lambda. Commented Sep 27, 2024 at 18:47
  • This question is similar to: How do I merge two dictionaries in a single expression in Python?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Sep 27, 2024 at 18:53
  • 2
    The question is valid, even if the example use of the lambda expression is an anti-pattern. Commented Sep 27, 2024 at 18:55
  • @IgnatiusReilly They said that's an Example. Of the more general thing they want. Commented Sep 27, 2024 at 18:55

1 Answer 1

2

You could use dict unpacking and packing:

dict_update = lambda d, upd: {**d, **upd}
Sign up to request clarification or add additional context in comments.

2 Comments

Or dict_update = dict.__or__.
@mins How does this answer anything other than your example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.