How to sort Python dict (dictionary)
26th September 2007
Sample script (copypasted from Well House Consultants training course):
click the PLAIN TEXT header for copy-pasteable version
PYTHON:
-
#!/usr/local/bin/python
-
-
author = {"php":"Rasmus Lerdorf",\
-
"perl":"Larry Wall",\
-
"tcl":"John Ousterhout",\
-
"awk":"Brian Kernighan",\
-
"java":"James Gosling",\
-
"parrot":"Simon Cozens",\
-
"python":"Guido van Rossum"}
-
-
langs = author.keys()
-
langs.sort()
-
-
for language in langs:
-
print language,"is the child of",author[language]
You can also define the Python ksort() function similar to that found in PHP:
PYTHON:
-
def ksort(d, func = None):
-
keys = d.keys()
-
keys.sort(func)
-
return keys
-
-
# example use, assume 'd' is a dictionary
-
for k in ksort(d):
-
print k, d[k]
(example taken from TheScript forum)
June 3rd, 2009 at 12:50
[...] - Python: good MySQLdb tutorial (examples)Good Python starter’s guideHow to sort Python dict (dictionary)Python: iterate (and read) all files in a directory (folder)Non-Programmer’s Tutorial for [...]