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)

Labels:

0 Comments:

Post a Comment

<< Home


[/home] [blog home]

07/01/2002 - 08/01/2002 08/01/2002 - 09/01/2002 09/01/2002 - 10/01/2002 10/01/2002 - 11/01/2002 11/01/2002 - 12/01/2002 02/01/2005 - 03/01/2005 03/01/2005 - 04/01/2005 04/01/2005 - 05/01/2005 05/01/2005 - 06/01/2005 06/01/2005 - 07/01/2005 07/01/2005 - 08/01/2005 08/01/2005 - 09/01/2005 09/01/2005 - 10/01/2005 11/01/2005 - 12/01/2005 12/01/2005 - 01/01/2006 01/01/2006 - 02/01/2006 02/01/2006 - 03/01/2006 03/01/2006 - 04/01/2006 04/01/2006 - 05/01/2006 05/01/2006 - 06/01/2006 06/01/2006 - 07/01/2006 07/01/2006 - 08/01/2006 08/01/2006 - 09/01/2006 09/01/2006 - 10/01/2006 10/01/2006 - 11/01/2006 11/01/2006 - 12/01/2006 12/01/2006 - 01/01/2007 01/01/2007 - 02/01/2007 02/01/2007 - 03/01/2007 03/01/2007 - 04/01/2007 05/01/2007 - 06/01/2007 06/01/2007 - 07/01/2007 07/01/2007 - 08/01/2007 08/01/2007 - 09/01/2007 09/01/2007 - 10/01/2007 10/01/2007 - 11/01/2007 11/01/2007 - 12/01/2007 12/01/2007 - 01/01/2008 01/01/2008 - 02/01/2008 02/01/2008 - 03/01/2008 03/01/2008 - 04/01/2008 04/01/2008 - 05/01/2008 05/01/2008 - 06/01/2008 06/01/2008 - 07/01/2008