3 ms·
Your defaultdict approach and the dict.get with a default specified is not really equivalent. In the defaultdict case when you encounter a non existing key it a
by europa 12y ago
Your defaultdict approach and the dict.get with a default specified is not really equivalent. In the defaultdict case when you encounter a non existing key it adds a new entry with that key into the dict. i.e. your dict will start growing.
whereas dic.get with default value keep returning you the default value without touching your dict.
- ghshephard 12y agore: "Your defaultdict approach and the dict.get with a default specified is not really equivalent. In the defaultdict case when you encounter a non existing key it adds a new entry with that key into the dict. i.e. your dict will start growing." europa - The dictionary is only modified if you are using a method to modify it. When you are just passively querying it, it's not impacted. class defaultdict(dict): def __init__(self, default=None): dict.__init__(self) self.default = default def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return self.default mdict=defaultdict(0) mdict['gordon']=10 mdict['tim']=20 print mdict['gordon'] print mdict['tim'] print mdict['george'] print mdict 10 20 0 {'tim': 20, 'gordon': 10}
- europa 12y agoYou are right about your implementation. I was thinking about the Pythons collections.defaultdict from collections import defaultdict s = 'mississippi' d = defaultdict(int) for k in s: d[k] += 1 d.items() [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
- ghshephard 12y agoThe difference here - is that you are actually assigning a value to the dictionary element. It's the assignment that's growing the dictionary, not the query.