setdefault

python dict: get vs setdefault

python dict: get vs setdefault Question: 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 …

Total answers: 8

Use cases for the 'setdefault' dict method

Use cases for the 'setdefault' dict method Question: The addition of collections.defaultdict in Python 2.5 greatly reduced the need for dict‘s setdefault method. This question is for our collective education: What is setdefault still useful for, today in Python 2.6/2.7? What popular use cases of setdefault were superseded with collections.defaultdict? Asked By: Eli Bendersky || …

Total answers: 18