0

I have a nested dictionary of type following

{id_1 : [ {id_2:score},{id_3:score_2} .... and so on],id_2 :[{id_1:Score_!....]}

so basically a nested dictionary Now I want to sort this dictionary per primary id on the basis of score so basically

{id_1: [{element with max_score},{element_with next max_score....}]... id_2:[{element_with max_score},{element_with next maxx score}...]

also, the function should take an argument say (n) which returns the top n matches or if the n< number of elements of that id then it returns teh complete list any Ideas/ thoughts.. Thanks

4
  • You probably have a spurious bracket in the first code snippet -- could you please review this? Commented Nov 21, 2011 at 19:10
  • Why are the values of the inner list dictionaries, and not just tuples? Commented Nov 21, 2011 at 19:10
  • @SvenMarnach yepp yepp . Thanks for pointing that out.. basically its a nested dictionary Commented Nov 21, 2011 at 19:11
  • in-place or you want a new object? Commented Nov 21, 2011 at 19:42

1 Answer 1

3

You can use the key parameter to list.sort(). Assuming the outer dictionary is called d, the code could look like this:

for scores in d.itervalues():
    scores.sort(key=lambda x: next(x.itervalues()), reverse=True)

The lambda function simply extracts the single value of the dictionary.

I think you'd be better off using tuples instead of dictionaries as the values of your list:

{id_1: [(id_2, score_2), (id_3, score_3),...], id_2: [(id_1, score_1),...]}

Using this data structure, the sorting code would be

for scores in d.itervalues():
    scores.sort(key=lambda x: x[1], reverse=True)

or equivalently, but slightly faster

for scores in d.itervalues():
    scores.sort(key=operator.itemgetter(1), reverse=True)
Sign up to request clarification or add additional context in comments.

4 Comments

Should that be scores.sort(...)?
So is d the list.. or a nesteddict??
+1, might need reverse=True as well since the OP wants higher scores first.
@Jerod I don't understand. This answer contains three possible solutions, and the first one is based on the exact data structure the OP provided. How does this not answer the original question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.