Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a sequence of sequences to a dictionary and vice-versa

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)}
like image 840
Louis Avatar asked May 06 '10 04:05

Louis


People also ask

How do you make a list into a dictionary?

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.

Is a dictionary a type of sequence?

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.

Are dictionaries a sequence?

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.

Is a dictionary a sequence in Python?

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.


2 Answers

mydict = dict((s[0], s[1:]) for s in myseq)

myseq = tuple(sorted((k,) + v for k, v in mydict.iteritems()))
like image 193
Alex Martelli Avatar answered Oct 18 '22 13:10

Alex Martelli


>>> 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.

like image 2
Chris AtLee Avatar answered Oct 18 '22 13:10

Chris AtLee