943,981 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 1103
  • Python RSS
You are currently viewing page 1 of this multi-page discussion thread
Nov 8th, 2009
0

Dictionary Sorting By Values Other Than Keys

Expand Post »
Hello everyone,

I'm learning Python and I have a few questions about Dictionaries and sorting them by a value other than the key.

Lets say, for example, I have a Dictionary full of data that needs to be sorted on the 3rd value instead of the key. How would I go about doing this? I have tried just the .sort() and that just sorts by the key.

So if,

Data = [('1023', ['Name', '3.1', 'SomeData']), ('1000', ['SomeName', '4.0', 'MoreData'])

how would I sort "Data" by the value where 3.1 is?

Please forgive my lack of correct terminology if I am missing some somewhere! Any help would be greatly appreciated.
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
xm1014 is offline Offline
6 posts
since Apr 2008
Nov 8th, 2009
1
Re: Dictionary Sorting By Values Other Than Keys
It doesn't look like you're using a dictionary. It appears that you have a list of tuples, and each tuple consists of a string and a list.

I can't think of a built in way to do this. You might have to look at writing your own version of a bubble sort or something. To do that, you would go through the entire outer list and compare the 2nd element of the inner list. If they are not in the correct order, then switch them around. Repeat until you can go through the whole list without having to make any switches.
Reputation Points: 16
Solved Threads: 35
Junior Poster
mn_kthompson is offline Offline
148 posts
since Nov 2007
Nov 8th, 2009
0
Re: Dictionary Sorting By Values Other Than Keys
You can use the 'key' argument to 'sort' or 'sorted'. Here, Data is a list. You can write
python Syntax (Toggle Plain Text)
  1. def my_key(item):
  2. return item[1][1] # this returns 3.1 if item is ('1023', ['Name', '3.1', 'SomeData'])
  3.  
  4. Data.sort(key = my_key)
Data is easily turned into a dictionary:
Python Syntax (Toggle Plain Text)
  1. Data = dict(Data)
  2. L = sorted(Data.items(), key = my_key)
Reputation Points: 930
Solved Threads: 668
Posting Maven
Gribouillis is offline Offline
2,655 posts
since Jul 2008
Nov 8th, 2009
1
Re: Dictionary Sorting By Values Other Than Keys
Similar to Gribouillis' code, but uses lambda as a helper function ...
python Syntax (Toggle Plain Text)
  1. # sort a more complex combination of lists/tuples:
  2. mylist = [
  3. (1, ['a', '3.1', 'ad']),
  4. (2, ['b', '4.0', 'bd']),
  5. (3, ['c', '2.5', 'cd']),
  6. ]
  7. # sort by item at index [1][1] of each tuple
  8. # using a helper function like lambda
  9. newlist = sorted(mylist, key=lambda tup: tup[1][1])
  10.  
  11. print newlist
  12.  
  13. """my result (made pretty) -->
  14. [
  15. (3, ['c', '2.5', 'cd']),
  16. (1, ['a', '3.1', 'ad']),
  17. (2, ['b', '4.0', 'bd'])
  18. ]
  19. """
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Nov 8th, 2009
1
Re: Dictionary Sorting By Values Other Than Keys
You can also use a somewhat older concept of sorting, the Schwartzian transform algorithm. This is made very easy with Python's list comprehension ...
python Syntax (Toggle Plain Text)
  1. # sort a more complex combination of lists/tuples:
  2.  
  3. mylist = [
  4. (1, ['a', '3.1', 'ad']),
  5. (2, ['b', '4.0', 'bd']),
  6. (3, ['c', '2.5', 'cd']),
  7. ]
  8.  
  9. # use the Schwartzian transform algorithm
  10. # temporarily put a copy of indexed item in front
  11. templist = [(x[1][1], x) for x in mylist]
  12. templist.sort()
  13. # remove temporary front item after sorting
  14. newlist = [val for (temp, val) in templist]
  15.  
  16. print newlist
  17.  
  18. """my result (made pretty) -->
  19. [
  20. (3, ['c', '2.5', 'cd']),
  21. (1, ['a', '3.1', 'ad']),
  22. (2, ['b', '4.0', 'bd'])
  23. ]
  24. """
Last edited by vegaseat; Nov 8th, 2009 at 8:37 pm.
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Nov 10th, 2009
0
Re: Dictionary Sorting By Values Other Than Keys
I've tried all three of these methods, however, I haven't been able to get them to work correctly for my particular set of data. I believe I may have pasted my dictionary incorrectly.

Here is what I have in my dictionary:
data = {'1234': ['Matt', '2.5', 'CS'], '1000': ['John', '4.0', 'Music'], '1023': ['Aaron', '3.1', 'PreMed'], '1001': ['Paul', '3.9', 'Music'], '9000': ['Kris', '3.5', 'Business']}

Would this have affected the methods of sorting that were mentioned?
Last edited by xm1014; Nov 10th, 2009 at 4:38 am.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
xm1014 is offline Offline
6 posts
since Apr 2008
Nov 10th, 2009
1
Re: Dictionary Sorting By Values Other Than Keys
So you have a dictionary after all!

Dictionaries are indexed by key and the keys are in a hash order for fast lookups. They will always display in this order! If you want to sort by a certain item, you have to convert them to lists. I thought that is what you did.

Python Syntax (Toggle Plain Text)
  1. data_dict = {
  2. '1234': ['Matt', '2.5', 'CS'],
  3. '1000': ['John', '4.0', 'Music'],
  4. '1023': ['Aaron', '3.1', 'PreMed'],
  5. '1001': ['Paul', '3.9', 'Music'],
  6. '9000': ['Kris', '3.5', 'Business']
  7. }
  8.  
  9. # convert dictionary to a list of tuples
  10. data_list = [(key, val) for key, val in data_dict.items()]
  11.  
  12. print(data_list)
  13. """the raw list -->
  14. [
  15. ('1234', ['Matt', '2.5', 'CS']),
  16. ('9000', ['Kris', '3.5', 'Business']),
  17. ('1001', ['Paul', '3.9', 'Music']),
  18. ('1023', ['Aaron', '3.1', 'PreMed']),
  19. ('1000', ['John', '4.0', 'Music'])
  20. ]
  21. """
  22.  
  23. # now you can sort the list by item[1][1]
  24. sorted_list = sorted(data_list, key=lambda tup: tup[1][1])
  25.  
  26. print(sorted_list)
  27. """result sorted by item[1][1] -->
  28. [
  29. ('1234', ['Matt', '2.5', 'CS']),
  30. ('1023', ['Aaron', '3.1', 'PreMed']),
  31. ('9000', ['Kris', '3.5', 'Business']),
  32. ('1001', ['Paul', '3.9', 'Music']),
  33. ('1000', ['John', '4.0', 'Music'])]
  34. """
  35.  
  36. # however if you go back to a dictionary
  37. new_dict = dict(sorted_list)
  38.  
  39. print(new_dict)
  40. """result is the dictionary order again -->
  41. {
  42. '1234': ['Matt', '2.5', 'CS'],
  43. '1000': ['John', '4.0', 'Music'],
  44. '1001': ['Paul', '3.9', 'Music'],
  45. '1023': ['Aaron', '3.1', 'PreMed'],
  46. '9000': ['Kris', '3.5', 'Business']}
  47. """
So, if you want to do any processing that needs a sorted order, to have to convert your dictionary to a temporary list.
Last edited by vegaseat; Nov 10th, 2009 at 9:16 am.
Moderator
Reputation Points: 1333
Solved Threads: 1403
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Nov 10th, 2009
0
Re: Dictionary Sorting By Values Other Than Keys
Ah ha! That worked! Now, since you're putting it in a list to sort the values, is there also a way to separate those values you are sorting on into a list by themselves?
Reputation Points: 10
Solved Threads: 0
Newbie Poster
xm1014 is offline Offline
6 posts
since Apr 2008
Nov 10th, 2009
0
Re: Dictionary Sorting By Values Other Than Keys
Click to Expand / Collapse  Quote originally posted by xm1014 ...
Ah ha! That worked! Now, since you're putting it in a list to sort the values, is there also a way to separate those values you are sorting on into a list by themselves?
Is this what you mean?

python Syntax (Toggle Plain Text)
  1. >>> my_dict = {'a':1, 'b':2, 'c':3}
  2. >>> my_dict.keys()
  3. ['a', 'c', 'b']
  4. >>> my_dict.values()
  5. [1, 3, 2]
  6. >>>
Reputation Points: 355
Solved Threads: 292
Veteran Poster
jlm699 is offline Offline
1,102 posts
since Jul 2008
Nov 10th, 2009
0
Re: Dictionary Sorting By Values Other Than Keys
Click to Expand / Collapse  Quote originally posted by jlm699 ...
Is this what you mean?

python Syntax (Toggle Plain Text)
  1. >>> my_dict = {'a':1, 'b':2, 'c':3}
  2. >>> my_dict.keys()
  3. ['a', 'c', 'b']
  4. >>> my_dict.values()
  5. [1, 3, 2]
  6. >>>
Not exactly, I'd like to take the values that are being sorted on and put them into a new list/dict etc.

For example, extracting only these values from the dictionary above:
new_list = ('2.5','3.5','3.9','4.0','3.1')
Reputation Points: 10
Solved Threads: 0
Newbie Poster
xm1014 is offline Offline
6 posts
since Apr 2008

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: Several values to one key
Next Thread in Python Forum Timeline: Singletonize any class





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC