If Dict Contains a particular key

Steve Holden steve at holdenweb.com
Thu Apr 26 13:51:19 CEST 2007


Gabriel Genellina wrote:
> En Thu, 26 Apr 2007 03:56:17 -0300, John Nagle <nagle at animats.com>  
> escribió:
> 
>>>>>> On Tue, 2007-04-24 at 18:28 +0100, Robert Rawlins - Think Blue wrote:
>>>>>>> I'm Looking to build a quick if/else statement that checks a
>>>>>>> dictionary for a key like follows.
>>      It would be useful if there was some direct way to get the value
>> associated with a key, and None if there's not one.
> 
> Such wonderful method exists since immemorial ages -at least since Python  
> 1.5- and its magic name is "get":
> 
> py> d = {'a': 1, 'b': 2}
> py> print d.get("a")
> 1
> py> print d.get("z")
> None
> 
Or, if you are using 2.5, look at collections.defaultdict:

   http://docs.python.org/lib/defaultdict-objects.html#l2h-735

regards
  Steve
-- 
Steve Holden       +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Recent Ramblings       http://holdenweb.blogspot.com




More information about the Python-list mailing list