Reputation: 29557
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'
Upvotes: 0
Views: 158
Reputation: 250931
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
Upvotes: 0
Reputation: 133544
>>> steps = {"5":{}, "1":{}}
>>> for k in sorted(steps, key=int):
print k, steps[k]
1 {}
5 {}
Upvotes: 2