3 ms·
I find I use it most in multi-level data structures, not unlike Perl's auto-vivification system: logins = {} for user, date in getLogins(): login
by Erwin 14y ago
I 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.