tags:

views:

59

answers:

4
+1  Q: 

sorting in python

I have a hashmap like so:

results[tweet_id] = {"score" : float(dot(query,doc) / (norm(query) * 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.

+4  A: 
>>> 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}]
S.Mark
But I think his `results` is a `dict`, not a `list`, and therefore can't be sorted.
Tim Pietzcker
@Tim: `results` is a `list` of `dict` s, and since the values are hashable, it can be sorted. :]
Xavier Ho
Yes, in @S.Mark's code it is, but not in @tipu's code. Am I wrong?
Tim Pietzcker
@TimPietzcker, you were correct to say that my code was a dict of dicts. However I have changed results to be a list of dict.
tipu
+2  A: 

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"))
Michael Aaron Safyan
+1  A: 

You can sort it using a custom comparison function like this:

results.sort(key=lambda x:x['score'])
Olivier
+1  A: 

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}]
Tim Pietzcker
+1 for converting it to sortable array.
S.Mark