Wednesday, March 19, 2008

python dictionaries

This is yet another 'putting things on my blog so that i can find them again' post. And because I remember stuff better once I've written it out.

I'm really a perl developer at heart, so I think in terms of hashes (you can see the post right tools for how nuts I am). Python, which I'm using for a little project I dreamed up to torture myself make my life easier, doesn't Do Hashes like perl does. Instead, you use "dictionaries".

I just borrowed o'reilly's python pocket reference from another developer, and here are the notes from the dictionaries reference in it.

adict = { 'info': { 42: 1, type("): 2 }, 'spam': [] } ==> adict['info'][42] is "1"

adict = dict(name='bob', age=42, job=('mg', 'dev'))

adict = dict(zip('abc', [1,2,3]))


Operations

adict.has_key(k) or k in adict

print d.get('key', 'not found')

adict.setdefault(key, []).append(number) (use value if it's in there, otherwise add to it)

adict.keys() -list of keys
adict.values() - list of values
adict.items() - list of k,v pairs

adict.clear() - wipe it

adict.copy()
adict.update(anotherdict) or adict.update(k1=v1, k2 = v2)

adict.popitem() - arbitrary item

adict.pop(k, [,x]) = get value stored at k (and remove k) if it was in there. otherwise, return x

adict.fromkeys(seq, [, value]) - new dictionary with keys from "seq" and values all initialized to "value"

adict.iteritems(), adict.iterkeys(), adict.itervalues() - go over the sets


(this is also mixed with things from the python cookbook)

No comments: