views:

58

answers:

2

One way to manually persist a dictionary to a database is to flatten it into a sequence of sequences and pass the sequence as an argument to cursor.executemany().

The opposite is also useful, i.e. reading rows from a database and turning them into dictionaries for later use.

What's the best way to go from myseq to mydict and from mydict to myseq?

>>> myseq = ((0,1,2,3), (4,5,6,7), (8,9,10,11))

>>> mydict = {0: (1, 2, 3), 8: (9, 10, 11), 4: (5, 6, 7)}
+5  A: 
mydict = dict((s[0], s[1:]) for s in myseq)

myseq = tuple(sorted((k,) + v for k, v in mydict.iteritems()))
Alex Martelli
Thanks! I don't actually need the list sorted.
Louis
+2  A: 
>>> mydict = dict((t[0], t[1:]) for t in myseq))

>>> myseq = tuple(((key,) + values) for (key, values) in mydict.items())

The ordering of tuples in myseq is not preserved, since dictionaries are unordered.

Chris AtLee