0

x is a tuple: (x1, x2)

try:
    clusters[bestmukey].append(x)  # statment 1
except KeyError:
    clusters[bestmukey] = [x]      # statement 2

(1) How do statement 1 and statement 2 do different things?

(2) Why are the separated statements needed?

2
  • Assuming clusters is a dictionary, statement 1 adds an element to a value that is a list, if the key, value pair have not been initialized, the key error will be raised; hence, statement 2, which creates a new key, value pair. Commented Oct 6, 2014 at 0:35
  • dict.setdefault would probably do the same without the try/except Commented Oct 6, 2014 at 0:40

3 Answers 3

3

clusters[bestmukey].append(x) requires that clusters[bestmukey] already exist and be a list that can be appended to. If clusters does not have the right key, this will raise KeyError.

clusters[bestmukey] = [x] will always work (as long as clusters is a dictionary, which is what I'm assuming), and sets the value to a new list with one element.

The effect of the code is to create a list with a new single value if the key does not already exist, or add the value to the existing list if it does already exist.

The same effect could be achieved without a try/except by using a defaultdict. The defaultdict effectively wraps this logic into itself.

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

Comments

0

Apparently clusters is a dict whose values are lists. This code tries to append to such a list if the key bestmukey exists, but if it does not, it adds the key and starts a list.

It would usually be preferable to use a defaultdict

Comments

0

clusters[bestmukey] = ... in statement #2 will write to clusters[bestmukey], no matter what (it's called an lvalue, a left value, something you assign to). However, clusters[bestmukey] in statement #1 is an rvalue (not something you assign to), and in Python's mind it needs to exist, or you get an error. Even if you didn't get an error (like in Ruby or other languages), you would not have gotten something that you can append on*, so statement #1 is not applicable.


*) You can, with defaultdict. But that's another story.

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.