Handling sorted dictionaries

filyph filyph at gmail.com
Tue Apr 17 04:41:31 EDT 2007


Hello,

Dictionary items are inordered and can not be sorted. Function
sorted() returns list of tuples in each is 0. item key from dictionary
and 1. is value from key-value pair from dict machines. List indices
must be integers and machine keys are strings. See http://www.python.org/dev/peps/pep-0265/
about sorting dictionaries.
You need to know what type is variable in each line of code.
Dict is not same as list, even when you can get values from they very
similar way. dict[key] and list[index], key can be everything what can
be hashed, but index can be only integer.

I am not english, so I hope you understand me.

loial napísal(a):
> 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?
> machinekey = "111111"
> machines = {}
> machines[machinekey]=[1,0,0,0,0,0,0,0,0,0,0,0,0]
> machinekey = "222222"
> machines[machinekey]=[0,1,0,0,0,0,0,0,0,0,0,0,0]
> ddd=0
> for machine in machines.keys():
>            d=machines[machine]
>            print machine
>            print d [ddd]
>
> sortedmachines=sorted(machines)
> for machine in sortedmachines:
>           d=sortedmachines[machine]
>           print machine
>           print d [ddd]




More information about the Python-list mailing list