Newbie Questions: Swithing from Perl to Python

Todd Stephens huzzah at tampabay.rr.com
Sat Oct 25 21:56:35 EDT 2003


On Sat, 25 Oct 2003 21:34:23 -0400, Luther Barnum wrote:

> 2. How can I sort and print out a hash.
> 
> Example in Perl:
> 
> ex. foreach $string (sort keys %hash) {
>      print("$string = $hash{$string}\n");
>      }
>      }

Well, as a Python learner myself, I am going to attempt this for my own
education as well.  I think you are looking for a dictionary in Python.
Let's say you have a dictionary 'dict' that contains something like this:

>>> dict = {'a':'me', 'b':'myself', 'c':'I'}

To print the dictionary as you iterate over it is simple:

>>> for key in dict:
...   print key, '=', dict[key]

This gives me:

a = me
c = I
b = myself

The order it prints could vary each time.  I am not sure how to print a
sorted list from a dictionary.  I think this would probably involve
assigning the dictionary elements to a list, then printing the sorted
list(s).  I would like to see the code for that myself.  BTW, Go Bucs.

-- 
Todd Stephens




More information about the Python-list mailing list