Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Korakot Chaovavanich http://korakot.stumbleupon.com

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

Collection of a bunch of named stuff

Taken from this recipe and its comments.
   1  
   2  class bunch(dict):
   3      def __init__(self,**kw):
   4          dict.__init__(self,kw)
   5          self.__dict__.update(kw)

Usage is simple.
   1  
   2  >>> o = bunch(a='A', b='B')
   3  >>> o
   4  {'a': 'A', 'b': 'B'}
   5  >>> o.a
   6  'A'
   7  >>> o.b
   8  'B'
   9  >>> 

You can use it as both an object and dict.

An interval mapping class

A kind of dictionary which allows you to map data intervals to values.
Download 'intervalmap' from this recipe page.
   1  
   2  >>> i = intervalmap()
   3  >>> i[0:5] = '0-5'
   4  >>> i[8:12] = '8-12'
   5  >>> print i[2]
   6  0-5
   7  >>> print i[10]
   8  8-12
   9  >>>

Ordered dictionary

This is part of the pythonutils package.
   1  
   2  od = OrderedDict()
   3  od['key1'] = 'value 1'
   4  od['key2'] = 'value 2'
   5  print od
   6  {'key1': 'value 1', 'key2': 'value 2'}
   7  
   8  print od.sequence
   9  ['key1', 'key2']
  10  od.sequence.reverse()
  11  print od
  12  {'key2': 'value 2', 'key1': 'value 1'}
  13  print od.sequence
  14  ['key2', 'key1']

This dict keeps its insertion order and you can do other
manipulations. See more details here

Default dictionary

I always want to do this, like I did in Perl.
   1  
   2  >> d = DefaultDict(0)
   3  >> d[key] += 1     # no need to use d.get or d.setdefault
   4  
   5  >> d = DefaultDict([])  # similarly with list value
   6  >> d[key].append(item)

See the implementation by Peter Norvig (of AI & Google fame)
here
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS