5 ms·
Another method that I find isn't used enough: dict.setdefault. Instead of doing this: if 'key' in d: val = d['key'] else: val = d['key
by someone13 14y ago
Another method that I find isn't used enough: dict.setdefault. Instead of doing this:
if 'key' in d:
val = d['key']
else:
val = d['key'] = 'some default value'
You can do this:
val = d.setdefault('key', 'some default value')
This is super-useful for configuration in frameworks, for example - it's a one-liner to set a default config value if the user didn't provide one.
- Erwin 14y agoI find I use it most in multi-level data structures, not unlike Perl's auto-vivification system: logins = {} for user, date in getLogins(): logins.setdefault(user, []).append(date) Here you login ends up having one key per "user" with a list of "date".
- thezilch 14y agoProbably better done with a defaultdict: from collections import defaultdict logins = defaultdict(list) for user, date in getLogins(): logins[user].append(date)
- gbog 14y agoif you have a lot of them, plain dict may prove faster.
- thezilch 14y agoNot likely. Proof? I'd agree if you'd said "not a lot of key/values," as the setup could supersede the subsequent speedups. However, in that case, the difference is negligible, and we should do what is "pythonic."
- gbog 14y agoYes, I meant a myriad of very small dicts. In this case a plain built-in is faster.
- brown9-2 14y agoI think you might have glossed over another very useful "shortcut" not covered in this article, the use of multiple assignments in a single statement.: val = d['key'] = 'some default value'