Autarchy of the Private Cave

Tiny bits of bioinformatics, [web-]programming etc

    • Archives

    • Recent comments

    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

    1. #!/usr/local/bin/python
    2.  
    3. author = {"php":"Rasmus Lerdorf",\
    4.     "perl":"Larry Wall",\
    5.     "tcl":"John Ousterhout",\
    6.     "awk":"Brian Kernighan",\
    7.     "java":"James Gosling",\
    8.     "parrot":"Simon Cozens",\
    9.     "python":"Guido van Rossum"}
    10.  
    11. langs = author.keys()
    12. langs.sort()
    13.  
    14. for language in langs:
    15.     print language,"is the child of",author[language]

    You can also define the Python ksort() function similar to that found in PHP:

    1. def ksort(d, func = None):
    2.     keys = d.keys()
    3.     keys.sort(func)
    4.     return keys
    5.  
    6. # example use, assume 'd' is a dictionary
    7. for k in ksort(d):
    8.     print k, d[k]

    (example taken from TheScript forum)

    Share

    One Response to “How to sort Python dict (dictionary)”

    1. Useful Python looping techniques »Autarchy of the Private Cave Says:

      [...] – 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 [...]

    Leave a Reply

    XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>