0

I have a python dictionary:

steps = {"5":{}, "1":{}}

I need to iterate this, but sorted by the keys as though they were ints. Key is always a number.

I tried:

def get_key_as_int(key):
    return int(key)

for key in sorted(steps.items(), key=lambda t: get_key_as_int(t[0])):
    step = steps[key]

but I get an error:

 unhashable type: 'dict'
4

2 回答 2

2
>>> steps = {"5":{}, "1":{}}
>>> for k in sorted(steps, key=int):
        print k, steps[k]


1 {}
5 {}
于 2013-05-23T10:20:04.137 回答
0

steps.items() returns key,value pairs(a list of tuples) not just keys. So in your code you were actually trying to do :

step = steps[ ('1', {}) ]

which will raise an error because keys can't contain mutable items.

Correct version of your code:

for key,step in sorted(steps.items(), key=lambda t: get_key_as_int(t[0])):
    #do something with step
于 2013-05-23T10:26:08.000 回答