[Idle-dev] Problem with Dictionaries

Rodrigo Dias Arruda Senra rodsenra at gpr.com.br
Tue Mar 1 22:02:46 CET 2005

Glauco Silva wrote:

> I´m with problem in Dictionaries !

since this question is not directly related to idle but to the language 
it should be addressed to comp.lang.python. In case you are a Portuguese
speaker person (guessing from your name), you could also seek help in
hte python-br mailing list.

In order to not let your question withou answer...

> I would like to know if the dictionary can sort with a function that i 
> give to then!

Dictionaries do not impose any particular order to their key/value pairs.
One possible  idiom to achieve what you want is the following:

# do not use dict as the name of your variable
# because 'dict' is the name and identifier of the class dict
 >>> d  = {}
 >>> d[50]="fifty"
 >>> d[129]="one hundred twenty nine"
 >>> d
{129: 'one hundred twenty nine', 50: 'fifty'}

# extract the keys
 >>> sorted_keys = d.keys()
# sort inplace, this returns None
 >>> sorted_keys.sort()
# traverse the dictionary using the sorted keys list
 >>> for i in sorted_keys:
             print d[i]
one hundred twenty nine

If you are using Python  2.4, you could also use:
 >>> for i in sorted(d.keys()):
            print d[i]

best regards,
Rod Senra

No virus found in this outgoing message.
Checked by AVG Anti-Virus.
Version: 7.0.300 / Virus Database: 266.5.4 - Release Date: 2005-03-01

More information about the IDLE-dev mailing list