Dictionary Sorting By Values Other Than Keys

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Apr 2008
Posts: 6
Reputation: xm1014 is an unknown quantity at this point 
Solved Threads: 0
xm1014 xm1014 is offline Offline
Newbie Poster

Dictionary Sorting By Values Other Than Keys

 
0
  #1
25 Days Ago
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.
Reply With Quote Quick reply to this message  
Join Date: Nov 2007
Posts: 147
Reputation: mn_kthompson is an unknown quantity at this point 
Solved Threads: 32
mn_kthompson mn_kthompson is offline Offline
Junior Poster
 
1
  #2
25 Days Ago
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.
Reply With Quote Quick reply to this message  
Join Date: Jul 2008
Posts: 932
Reputation: Gribouillis is a jewel in the rough Gribouillis is a jewel in the rough Gribouillis is a jewel in the rough 
Solved Threads: 216
Gribouillis's Avatar
Gribouillis Gribouillis is offline Offline
Posting Shark
 
0
  #3
25 Days Ago
You can use the 'key' argument to 'sort' or 'sorted'. Here, Data is a list. You can write
  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:
  1. Data = dict(Data)
  2. L = sorted(Data.items(), key = my_key)
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,028
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 932
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite
 
1
  #4
24 Days Ago
Similar to Gribouillis' code, but uses lambda as a helper function ...
  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. """
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,028
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 932
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite
 
1
  #5
24 Days Ago
You can also use a somewhat older concept of sorting, the Schwartzian transform algorithm. This is made very easy with Python's list comprehension ...
  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; 24 Days Ago at 8:37 pm.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Apr 2008
Posts: 6
Reputation: xm1014 is an unknown quantity at this point 
Solved Threads: 0
xm1014 xm1014 is offline Offline
Newbie Poster
 
0
  #6
23 Days Ago
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; 23 Days Ago at 4:38 am.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,028
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 932
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite
 
1
  #7
23 Days Ago
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.

  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; 23 Days Ago at 9:16 am.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Apr 2008
Posts: 6
Reputation: xm1014 is an unknown quantity at this point 
Solved Threads: 0
xm1014 xm1014 is offline Offline
Newbie Poster
 
0
  #8
22 Days Ago
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?
Reply With Quote Quick reply to this message  
Join Date: Jul 2008
Posts: 1,051
Reputation: jlm699 is a jewel in the rough jlm699 is a jewel in the rough jlm699 is a jewel in the rough jlm699 is a jewel in the rough 
Solved Threads: 264
Sponsor
jlm699's Avatar
jlm699 jlm699 is online now Online
Knows where his Towel is
 
0
  #9
22 Days Ago
Originally Posted by xm1014 View Post
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?

  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. >>>
1. Use Code Tags.
2. Homework? Show Effort.
3. Keep discussions on the forum: no PMs
Reply With Quote Quick reply to this message  
Join Date: Apr 2008
Posts: 6
Reputation: xm1014 is an unknown quantity at this point 
Solved Threads: 0
xm1014 xm1014 is offline Offline
Newbie Poster
 
0
  #10
22 Days Ago
Originally Posted by jlm699 View Post
Is this what you mean?

  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')
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC