| | |
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:
Solved Threads: 0
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.
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.
•
•
Join Date: Nov 2007
Posts: 147
Reputation:
Solved Threads: 32
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.
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.
0
#3 25 Days Ago
You can use the 'key' argument to 'sort' or 'sorted'. Here, Data is a list. You can write
Data is easily turned into a dictionary:
python Syntax (Toggle Plain Text)
def my_key(item): return item[1][1] # this returns 3.1 if item is ('1023', ['Name', '3.1', 'SomeData']) Data.sort(key = my_key)
Python Syntax (Toggle Plain Text)
Data = dict(Data) L = sorted(Data.items(), key = my_key)
1
#4 24 Days Ago
Similar to Gribouillis' code, but uses lambda as a helper function ...
python Syntax (Toggle Plain Text)
# sort a more complex combination of lists/tuples: mylist = [ (1, ['a', '3.1', 'ad']), (2, ['b', '4.0', 'bd']), (3, ['c', '2.5', 'cd']), ] # sort by item at index [1][1] of each tuple # using a helper function like lambda newlist = sorted(mylist, key=lambda tup: tup[1][1]) print newlist """my result (made pretty) --> [ (3, ['c', '2.5', 'cd']), (1, ['a', '3.1', 'ad']), (2, ['b', '4.0', 'bd']) ] """
May 'the Google' be with you!
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 ...
python Syntax (Toggle Plain Text)
# sort a more complex combination of lists/tuples: mylist = [ (1, ['a', '3.1', 'ad']), (2, ['b', '4.0', 'bd']), (3, ['c', '2.5', 'cd']), ] # use the Schwartzian transform algorithm # temporarily put a copy of indexed item in front templist = [(x[1][1], x) for x in mylist] templist.sort() # remove temporary front item after sorting newlist = [val for (temp, val) in templist] print newlist """my result (made pretty) --> [ (3, ['c', '2.5', 'cd']), (1, ['a', '3.1', 'ad']), (2, ['b', '4.0', 'bd']) ] """
Last edited by vegaseat; 24 Days Ago at 8:37 pm.
May 'the Google' be with you!
•
•
Join Date: Apr 2008
Posts: 6
Reputation:
Solved Threads: 0
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?
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.
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.
So, if you want to do any processing that needs a sorted order, to have to convert your dictionary to a temporary list.
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)
data_dict = { '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'] } # convert dictionary to a list of tuples data_list = [(key, val) for key, val in data_dict.items()] print(data_list) """the raw list --> [ ('1234', ['Matt', '2.5', 'CS']), ('9000', ['Kris', '3.5', 'Business']), ('1001', ['Paul', '3.9', 'Music']), ('1023', ['Aaron', '3.1', 'PreMed']), ('1000', ['John', '4.0', 'Music']) ] """ # now you can sort the list by item[1][1] sorted_list = sorted(data_list, key=lambda tup: tup[1][1]) print(sorted_list) """result sorted by item[1][1] --> [ ('1234', ['Matt', '2.5', 'CS']), ('1023', ['Aaron', '3.1', 'PreMed']), ('9000', ['Kris', '3.5', 'Business']), ('1001', ['Paul', '3.9', 'Music']), ('1000', ['John', '4.0', 'Music'])] """ # however if you go back to a dictionary new_dict = dict(sorted_list) print(new_dict) """result is the dictionary order again --> { '1234': ['Matt', '2.5', 'CS'], '1000': ['John', '4.0', 'Music'], '1001': ['Paul', '3.9', 'Music'], '1023': ['Aaron', '3.1', 'PreMed'], '9000': ['Kris', '3.5', 'Business']} """
Last edited by vegaseat; 23 Days Ago at 9:16 am.
May 'the Google' be with you!
0
#9 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?
python Syntax (Toggle Plain Text)
>>> my_dict = {'a':1, 'b':2, 'c':3} >>> my_dict.keys() ['a', 'c', 'b'] >>> my_dict.values() [1, 3, 2] >>>
•
•
Join Date: Apr 2008
Posts: 6
Reputation:
Solved Threads: 0
0
#10 22 Days Ago
•
•
•
•
Is this what you mean?
python Syntax (Toggle Plain Text)
>>> my_dict = {'a':1, 'b':2, 'c':3} >>> my_dict.keys() ['a', 'c', 'b'] >>> my_dict.values() [1, 3, 2] >>>
For example, extracting only these values from the dictionary above:
new_list = ('2.5','3.5','3.9','4.0','3.1')
![]() |
Similar Threads
- Sorting a dictionary (Python)
- Using a list as values in a dictionary? (Python)
- Why Isn't This Working? (Python)
- Variable Referenced Before Assignment (Python)
- Dictionary Sorting? (Python)
- Concatenating dictionary values and keys, isnt working :( (Python)
- Dictionary Keys (Python)
Other Threads in the Python Forum
- Previous Thread: Several values to one key
- Next Thread: Singletonize any class
| Thread Tools | Search this Thread |
address anydbm app bash beginner changecolor cipher class clear conversion coordinates corners curves definedlines development dictionary dynamic events examples excel feet file float format function generator getvalue gui handling homework images import input ip java keycontrol line linux list lists loan loop maintain matching maze millimeter mouse mysqldb number numbers output parsing path port prime programming projects py2exe pygame pymailer python queue random rational raw_input recursion recursive scrolledtext searchingfile shebang singleton slicenotation split string strings table tails terminal text thread threading time tlapse tooltip tuple tutorial type ubuntu unicode url urllib urllib2 valueerror variable variables vigenere web wx.wizard wxpython xlwt






