python dict: get vs setdefault
问题 The following two expressions seem equivalent to me. Which one is preferable? data = [('a', 1), ('b', 1), ('b', 2)] d1 = {} d2 = {} for key, val in data: # variant 1) d1[key] = d1.get(key, []) + [val] # variant 2) d2.setdefault(key, []).append(val) The results are the same but which version is better or rather more pythonic? Personally I find version 2 harder to understand, as to me setdefault is very tricky to grasp. If I understand correctly, it looks for the value of "key" in the