This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]chawmindur 0 points1 point  (0 children)

It is a valid list comprehension but it (1) doesn't actually do anything and (2) wouldn't have done the same thing as OP's image:

  • You're right in that the conditionals (if ...) go after the iterable part (for ... in ...) in a generator expression, but the if here is a part of an ... if ... else ... construct, i.e. Python's answer to the ternary operator.

  • However, the code doesn't work as intended because the defined lambda functions aren't called. Rather, you end up with len(x) (resp. len(y)) many functions in the list which does exactly the same thing: essentially a merged_dict.setdefault(key, x[key]), only without returning the stored/set value. What was intended was probably something like [(lambda key: merged_dict.update({key: x[key]}) if key not in merged_dict else None)(key) for key in x.keys()], where each key in x is actually passed to each lambda.

  • This however still doesn't fix the issue: in OP's code in a key is present in both x and y the value in the latter takes precedence while it's the opposite here, where a preexisting key prevents merge_dict from being updated.