python - A forgiving dictionary -


How do I create a forgiving dictionary (one that gives a default value if one KeyError is raised)

I'll get a KeyError in the following code example; For example

  a = {'one': 1, 'two': 2} print [[three]]  

to get in order Not one would be me 1. The exception is to catch or use.

I would not like to do this with my dictionary ...

 < Code> archive a = collections.defaultdict (lambda: 3) a.update ({'one': 1, 'two': 2}) print one ['three']  

Emits as 3 as you are required you can also create subclass and override __ unavailable , but When this defaultdict behavior is being watched (ignoring the exact missing key), you are so well Suit ...

Edit ... Unless , you are concerned about a every Once you have to look for an absentee key (which is part of the words of defaultdict ), and gradually get the behavior, but save some memory. For example, in the context of memory ...:

  & gt; & Gt; & Gt; Import systems and gt; & Gt; & Gt; A = collection .defaultdict (lambda: 'blah')> gt; & Gt; & Gt; Print Lennon (A), Size Gatesize (A) 0 140 & gt; & Gt; & Gt; I am in xrange (99): _ = a [i] ... and gt; & Gt; & Gt; Print lane (a), sys.getsizeof (a) 99 6284  

... defaultdict, basically empty, now 99 is the key to disappear previously that we looked up, and 6284 Takes the bytes (140 bits were taken while creating it when it was empty).

Optional Approach ...:

  & gt; & Gt; & Gt; Class Mandic (Dict): ... df __missing (___ (___, key): return 3 ... & gt; & Gt; & Gt; A = mydict () & gt; & Gt; & Gt; Print Lennon (A), Size Gatesize (A) 0 140 & gt; & Gt; & Gt; I am in xrange (99): _ = a [i] ... and gt; & Gt; & Gt; Take a print (A), sys.getsizeof (A) 0 140  

... completely saves this memory overhead, as you see. Of course, performance is another issue:

  $ python -mtimeit -s'import archive; A = collections.defaultdict (int); R = xrange (99) '' i in r: _ = a [i] '100000 loops, get the best 3: 14.9 per five pythons - meteit -us-class mydict (dict): & gt; Def __missing __ (self, key): return 0> '-s'a = mydict (); R = xrange (99) '' for me: _ = a [i] '10000 loops, best 3: 92.9 per loop per usec  

Since defaultdict (pre-unavailable) key on the look-up, when such a key is seen next time, while mydict (which is to avoid that extra __ unavailable ) every time the "unavailable keys look overhead" pays.

Whether you care about any problem (performance versus memory footprint), exactly depends on the case of your specific use, of course. It is in any case is a good idea to know about business!) -


Comments

Popular posts from this blog

c# - sqlDecimal to decimal clr stored procedure Unable to cast object of type 'System.Data.SqlTypes.SqlDecimal' to type 'System.IConvertible' -

Calling GetGUIThreadInfo from Outlook VBA -

Obfuscating Python code? -