0

The author of the top answer of this question uses a lamda function as parameter for this function:

>>> d1 = {'one':1, 'both':3, 'falsey_one':False, 'falsey_both':None}
>>> d2 = {'two':2, 'both':30, 'falsey_two':None, 'falsey_both':False}


def dict_ops(d1, d2, setop):
...     """Apply set operation `setop` to dictionaries d1 and d2
... 
...     Note: In cases where values are present in both d1 and d2, the value from
...     d1 will be used.
...     """
...     return {k:d1.get(k,k in d1 or d2[k]) for k in setop(set(d1), set(d2))}

Like this:

>>> print "d1 - d2:", dict_ops(d1, d2, lambda x,y: x-y)

Which returns:

d1 - d2: {'falsey_one': False, 'one': 1}

I tried to do the same thing but not as a function, because I want to understand how the setop part works.

{k:d1.get(k,k in d1 or d2[k]) for k in lambda d1,d2: set(d1) - set(d2)}

However this code returns a syntax error.

But this works:

l = lambda d1,d2: set(d1) - set(d2)
{k:d1.get(k,k in d1 or d2[k]) for k in l(d1,d2)}

Why does the second solution work, but the first one dont?

If I call the dict_ops function with these parameters (d1, d2, lambda x,y: x-y) how does setop(set(d1) - set(d2) look like?

3
  • 3
    You're not calling the lambda. (lambda d1,d2: set(d1) - set(d2))(d1, d2) would work. Commented Jun 10, 2020 at 14:52
  • So I need to provide the lambda function with paramters? Was my mistake that I just 'wrote' a lambda function without providing parameters? Commented Jun 10, 2020 at 14:56
  • 1
    That's part of it. It would be syntactically valid if you just surrounded it with parentheses, but you'd get a TypeError ('function' object is not iterable) instead. You can define a lambda function without calling it, that's just not what you actually want to do here. Commented Jun 10, 2020 at 14:57

1 Answer 1

1

If you do an exact substitution, it will work. You have:

{... for k in setop(set(d1), set(d2))}

The value passed in for setop is:

lambda x,y: x-y

A direct substitution of setop is:

{... for k in (lambda x,y: x-y)(set(d1), set(d2))|

which will work.

For the second version, you have:

{... for k in l(d1,d2)}

where l is:

lambda d1,d2: set(d1) - set(d2)

A direct substitution here produces:

{... for k in (lambda d1,d2: set(d1) - set(d2))(d1,d2)}

which will also work.

Sign up to request clarification or add additional context in comments.

Comments

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.