sorting in python
I have a hashmap like so:
results[tweet_id] = {"score" : float(dot(query,doc) / (norm(query) *开发者_StackOverflow norm(doc))), "tweet" : tweet}
What I'd like to do is to sort results by the innser "score" key. I don't know how possible this is, I saw many sorting tutorials but they were for simple (not nested) data structures.
>>> results=[{"s":1,"score":100},{"s":2,"score":101},{"s":3,"score":99},{"s":4,"score":1},{"s":5,"score":1000}]
>>> from operator import itemgetter
>>> sorted(results, key=itemgetter("score"))
[{'s': 4, 'score': 1}, {'s': 3, 'score': 99}, {'s': 1, 'score': 100}, {'s': 2, 'score': 101}, {'s': 5, 'score': 1000}]
You can sort it using a custom comparison function like this:
results.sort(key=lambda x:x['score'])
You can use sorted with operator.itemgetter in order to use the "score" value as the key:
sorted_results = sorted(results,key=operator.itemgetter("score"))
Assuming that your results
is a dict
(because you called it a hashmap, and because I'm guessing that tweet_id
is a dictionary key, not a counter), you need to convert it to a list first in order to be able to sort it. In Python 3:
results = {}
results["1234"] = {"score": 123, "tweet": "Hello"}
results["4321"] = {"score": 321, "tweet": "there"}
results["abcd"] = {"score": 111, "tweet": "sailor!"}
l=[]
for key, value in results.items(): # use .iteritems() in Python 2.x
l.append([key, value])
for item in sorted(l, key=lambda x: x[1]["score"]):
print(item)
will output
['abcd', {'tweet': 'sailor!', 'score': 111}]
['1234', {'tweet': 'Hello', 'score': 123}]
['4321', {'tweet': 'there', 'score': 321}]
精彩评论