简体   繁体   中英

String index out of range when sorting a dictionary of (string, float)

I have a dictionary mapping strings to floats that I want to sort. I can verify that the types of the values are correct, but when I try the sort I get an IndexError execption.

Below is a code snippet. The validation loop runs fine and then the call to sorted fails.

for k, v in metric.items():
    if not isinstance(v, float):
        print "Bad value %s for %s" % (k, str(v))
rank = sorted(metric, key=operator.itemgetter(1), reverse=True)


---> 10     rank = sorted(metric, key=operator.itemgetter(1), reverse=True)
     11 

IndexError: string index out of range

Any idea why this happens?

Edit: this passes too with no problem:

for h in metric.iteritems():
    if not isinstance(operator.itemgetter(1)(h), float):
        print "Bad value %s for %s" % (h[0], h[1])

You are only sorting the keys of the dictionary. Apparently some of your keys are only 1 character short, so you get an index error for key[1] (which is what operator.itemgetter(1)(key) would try and access).

If the expected output is a sorted sequence of keys, look up the value from the dictionary:

rank = sorted(metric, key=metric.get, reverse=True)

If you expected a sequence of (key, value) pairs, sort metric.items() :

rank = sorted(metric.items(), key=operator.itemgetter(1), reverse=True)

When sorting the dict.items() sequence, item[1] refers to the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM