2 ms·
Oh, 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
by mrfusion 13y ago
Oh, 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 13y agoYep, take a look! >>> import collections >>> dd = collections.defaultdict(int) >>> print dd['doesnt exist'] 0 >>> print dd defaultdict(<type 'int'>, {'doesnt exist': 0})
- kansface 13y agoUse .get() instead of [] to avoid setting the default value.
- ForHackernews 13y agoThat's what they said they're doing.
- zo1 13y 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 13y 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 13y agoWhat you have there will print 1.
- deleted 13y ago[deleted]