Handling sorted dictionaries
Steven D'Aprano
steve at REMOVEME.cybersource.com.au
Tue Apr 17 04:29:18 EDT 2007
On Tue, 17 Apr 2007 01:01:55 -0700, loial wrote:
> The following code gives the error
>
> d=sortedmachines[machine]
> TypeError: list indices must be integers
>
>
> What works for the unsorted dictionary does not work for the sorted
> dictionary.
> Can anyone help?
The error message you got tells you what the problem is. sortedmachines
is not a "sorted dictionary". There is no such thing -- dictionaries, also
known as "hash tables" in other languages, are unsorted. sortedmachines is
a _list_, just like the error message says, and the index must be an
integer.
> sortedmachines=sorted(machines)
sortedmachines is now the sorted _keys_ copied from machines. Try calling
"print sortedmachines" and looking at what you get.
> for machine in sortedmachines:
> d=sortedmachines[machine]
Try this instead:
d = machines[machine]
--
Steven D'Aprano
More information about the Python-list
mailing list