Autarchy of the Private Cave

Science, Society, Programming and Hobbies

  • Exits

  • Categories

  • Archives

  • Visitors' track

    Locations of visitors to this page
  • Tags list

  • Earn and spend


  • Exits

  • Ratings

    Science Blogs - Blog Top Sites website monitoring service
  • 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:
    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:

    PYTHON:
    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 This

    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>

     
    Close
    E-mail It