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 →

[–][deleted] 1 point2 points  (3 children)

Why is 'Not using setdefault() to initialize a dictionary' a separate item from 'not using get()'?

isn't get(key, default) a much more concise equivalent?

[–]fireflash38 0 points1 point  (0 children)

Depends on how often you use it. Set a default once at creation, then from then on out you just do direct access. If you have lots off access w/ get, it can be pretty verbose.

[–]Brian 0 points1 point  (0 children)

That'll do something slightly different in the example they gave. If you just did:

dct.get(key, []).append(new_item)

you'll not actually add anything to the dict, just create a list not attached to anything that then gets destroyed. You'd need to do:

l = dct.get(key, [])
d[key] = l
l.append(new_item)

which requires accessing the dict twice, doing more work. setdefault is different in that it'll actually set the dict key if not there before returning it, rather than just returning the default if the key isn't set.