Creating a list with holes

Denis McMahon denismfmcmahon at gmail.com
Fri Jan 3 13:07:10 EST 2014


On Fri, 03 Jan 2014 10:41:21 -0500, Larry Martell wrote:

> The holes would be between the items I put in. In my example above, if I
> assigned to [10] and [20], then the other items ([0..9] and [11..19])
> would have None.

>>> dic = { 10:6, 20:11}
>>> dic.get(10)
6
>>> dic.get(14)
>>> dic.get(27,"oh god there's nothing here")
"oh god there's nothing here"
>>> dic.get(99,None)
>>> dic.get(168,False)
False
>>> dic.get(20,"Boo Yah")
11
>>>

So a standard dictionary does this returning None (or any other default 
value you care to pass it) as long as you use the dict.get(key[,default]) 
method rather than dict[key] to return the value.

See also: 

http://stackoverflow.com/questions/6130768/return-none-if-dictionary-key-
is-not-available

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list