4 ms·
I would guess that the code tries to get the value for keys that do not exist in the defaultdict. Well, if the key does not exist then it is being added with th
by cefstat 12y ago
I would guess that the code tries to get the value for keys that do not exist in the defaultdict. Well, if the key does not exist then it is being added with the default value 'NA'. So in this way you can end up with a huge dictionary where most of the values are just 'NA'.
- mrfusion 12y agoOh, wait, so defaultdicts actually insert missed keys?? I thought they simply gave you a default value instead of a keyerror. If you're right, then that would certainly explain it.
- bryanh 12y agoYep, take a look! >>> import collections >>> dd = collections.defaultdict(int) >>> print dd['doesnt exist'] 0 >>> print dd defaultdict(<type 'int'>, {'doesnt exist': 0})
- kansface 12y agoUse .get() instead of [] to avoid setting the default value.
- ForHackernews 12y agoThat's what they said they're doing.
- zo1 12y agoCorrect. The behavior you are looking for is already in the standard dict class. You just pass in an extra parameter to the get method like so: dict.get("key", "my_default_value_if key_is_not_inserted_already")
- Someone 12y agoThey have to, because they cannot, in general, decide whether the lambda you gave it is idempotent _and_ returns an immutable value. For example, if you provide a function that returns an empty list, and do: l = foo['bar'] l.append('baz') print len(foo['bar']) That should print 2 (apologies if this isn't correct Python) If one had a defaultdict that took a default value in a language with enough reflection, you might be able to deduce that the lambda always returns a simple value such as 3.1415927, and not store copies in the dictionary.
- maxerickson 12y agoWhat you have there will print 1.
- deleted 12y ago[deleted]