Fabian Steiner
2006-01-27 21:01:37 UTC
Hallo!
Ich bin gerade dabei, mir eine eigene kleine SQL-Query-Klasse zu
schreiben, die mir beispielsweise aus einem übergebenem Dictionary
einen INSERT-Query zusammenbaut. Dabei durchlaufe ich das Dictionary
z.B. folgendermaßen:
for column in data.keys():
if column == data.keys()[-1]:
self._query += ("'%s'" + ')') % (column)
else:
self._query += ("'%s'" + ', ') % (column)
An anderer Stelle geschieht beinahe das gleiche noch einmal mit
data.values(). Im Python Tutorial
(http://docs.python.org/tut/node7.html#SECTION007500000000000000000)
findet man dazu z.B. nur folgendes:
"The keys() method of a dictionary object returns a list of all the
keys used in the dictionary, in arbitrary order (if you want it sorted,
just apply the sort() method to the list of keys). "
Unter http://docs.python.org/lib/typesmapping.html findet man dann aber
auch noch folgende Aussage:
"Keys and values are listed in an arbitrary order which is non-random,
varies across Python implementations, and depends on the dictionary's
history of insertions and deletions."
Zusammengefasst heißt das also, dass die Reihefolge beliebig ist [1],
aber nicht zufällig. Meine Frage ist nun, kann ich mich darauf
verlassen, dass die Reihenfolge von dict.keys() und dict.values()
gleich ist und dann nicht etwas die Zuordnung Key-Value überhaupt
nicht mehr stimmt. Gibt es denn eine bessere Lösungsmöglichkeit.
Vielen Dank für eure Hilfe!
Grüße,
Fabian
[1] Was heißt in diesem Fall beliebig?
Ich bin gerade dabei, mir eine eigene kleine SQL-Query-Klasse zu
schreiben, die mir beispielsweise aus einem übergebenem Dictionary
einen INSERT-Query zusammenbaut. Dabei durchlaufe ich das Dictionary
z.B. folgendermaßen:
for column in data.keys():
if column == data.keys()[-1]:
self._query += ("'%s'" + ')') % (column)
else:
self._query += ("'%s'" + ', ') % (column)
An anderer Stelle geschieht beinahe das gleiche noch einmal mit
data.values(). Im Python Tutorial
(http://docs.python.org/tut/node7.html#SECTION007500000000000000000)
findet man dazu z.B. nur folgendes:
"The keys() method of a dictionary object returns a list of all the
keys used in the dictionary, in arbitrary order (if you want it sorted,
just apply the sort() method to the list of keys). "
Unter http://docs.python.org/lib/typesmapping.html findet man dann aber
auch noch folgende Aussage:
"Keys and values are listed in an arbitrary order which is non-random,
varies across Python implementations, and depends on the dictionary's
history of insertions and deletions."
Zusammengefasst heißt das also, dass die Reihefolge beliebig ist [1],
aber nicht zufällig. Meine Frage ist nun, kann ich mich darauf
verlassen, dass die Reihenfolge von dict.keys() und dict.values()
gleich ist und dann nicht etwas die Zuordnung Key-Value überhaupt
nicht mehr stimmt. Gibt es denn eine bessere Lösungsmöglichkeit.
Vielen Dank für eure Hilfe!
Grüße,
Fabian
[1] Was heißt in diesem Fall beliebig?