I have a dictionary that looks like a = {'10': 2.0, '3': 2.0, '7': 1.0, '6': 1.0}
I use:
it = iter(sorted(nums.items()))
try:
while(True):
print it.next()
except StopIteration:
print "\n\n"
To print the elements ordered by key value but it doesn't work. I get
('10', 1.0)
('3', 1.6666666666666667)
('6', 1.0)
('7', 1.0)
which is not what I want. I also tried bunch of other stuff but those don't work as well.. any ideas ?
That is sorting the keys by their values as strings (that is, alphabetically- "1" comes before "3" comes before "6"...) rather than their integer value. If you want to sort the keys by their numerical value, you could do
iter(sorted(nums.items(), key=lambda x: int(x[0])))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With