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

« 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.
class bunch(dict):
    def __init__(self,**kw):
        dict.__init__(self,kw)
        self.__dict__.update(kw)

Usage is simple.
>>> o = bunch(a='A', b='B')
>>> o
{'a': 'A', 'b': 'B'}
>>> o.a
'A'
>>> o.b
'B'
>>> 

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.
>>> i = intervalmap()
>>> i[0:5] = '0-5'
>>> i[8:12] = '8-12'
>>> print i[2]
0-5
>>> print i[10]
8-12
>>>

Ordered dictionary

This is part of the pythonutils package.
od = OrderedDict()
od['key1'] = 'value 1'
od['key2'] = 'value 2'
print od
{'key1': 'value 1', 'key2': 'value 2'}

print od.sequence
['key1', 'key2']
od.sequence.reverse()
print od
{'key2': 'value 2', 'key1': 'value 1'}
print od.sequence
['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.
>> d = DefaultDict(0)
>> d[key] += 1     # no need to use d.get or d.setdefault

>> d = DefaultDict([])  # similarly with list value
>> 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