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)}
To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.
The dictionary is the first compound type that we've seen that is not a sequence, so we can't index or slice a dictionary.
Useful Functions. While dictionaries aren't sequences, some of the same functions will work with them. len(d) returns the number of elements in dictionary d. k in d returns True iff d contains an entry with key k.
Dictionaries are important data structures in Python that use keys for indexing. They are an unordered sequence of items (key-value pairs), which means the order is not preserved.
mydict = dict((s[0], s[1:]) for s in myseq)
myseq = tuple(sorted((k,) + v for k, v in mydict.iteritems()))
>>> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With