dictionary issue (and maybe PEP ... depending on the answer)
Manuel Garcia
news at manuelmgarcia.com
Mon Jun 2 12:10:36 EDT 2003
Cheap trick for 1-based lists, just have an extra 'None' in the 0th
position:
_month_names = [
None,
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December', ]
Steven Taschuk's code is the most general technique:
months = [(1, 'January'),
(2, 'February'),
# ...
]
monthdict = dict(months)
monthnames = [name for number, name in months]
Trivial to write a function:
def sorted_keys(dict0):
newlist = dict0.keys()[:]
newlist.sort()
return newlist
print [_months[i] for i in sorted_keys(_months)]
The reason Python doesn't have a 'return a sorted copy'
(non-destructive) built-in method for lists is that the fastest
sorting algorithms are all 'in-place' (destructive). Python has as a
rule "there is only one way to do it", so the 'in-place' sort was
chosen as the only built-in method. As you can see above, it is easy
to write your own 'non-destructive' sort.
The reason that list0.sort() returns 'None' when used in an
expression, is so that you will never use it in an expression! The
sort's 'in-place' behavior is thus made explicit.
Manuel
More information about the Python-list
mailing list