I'm using Python 3.5.2 and I have a dict
that contains as "keys" a Tuple of Strings, and as "values" an Integer from a count. I want to do a dual sort, where the first priority is the first string in the key, and the second priority is the integer value. See below for a more in depth explanation:
For example, I've got a Dict:
>>> print(unorderedDict.items())
dict_items([(('has', 'accomplished'), 1), (('new', 'french'), 1), (('pieces', 'machinery'), 1), (('in', 'those'), 1), (('east', 'on'), 1), (('sectarian', 'principles'), 1), ((',', 'are'), 10), (('all', 'countries'), 2)......])
It contains as the Key a Tuple of two Strings ex. ('has', 'accomplished')
and also a value that is an integer ex. 1
. Ex. all together: ([(('all', 'countries'), 2)])
.
This essentially contains all unique combinations of words found in a text, in Tuple form as the key, along with the number of times that unique combination of words appears in the text as the value which is an Integer.
I want a way to sort the unorderedDict
, 1st by the first string in the key tuple and 2nd by the value.
The purpose of this is so that I will have a list of words, plus the word most likely to follow it, and next in the list that same word plus the next most likely word to follow it in the text.
Example output:
dict_items([(('all', 'the'), 10), (('all', 'of'), 7), (('big', 'drums), 12), (('big', 'dogs') 6)......])
Notice how it is first sorted by the first string in the tuple (alphabetically), and second by the value (numerically highest to lowest).
What Python 3 code would I need in order to perform this type of sorting algorithm?
The main reason for needing this sorting algorithm is so that I can randomly select one of the first strings in the tuple and get the second string in the tuple that is found more often (identified by the Integer from Count).
For example, I could randomly select 'all' and see that it is more likely to be followed by 'the' than it is by 'of' (vount of 'the' = 10, vount of 'of' = 7).
From my own research I assume it will have something to do with built-in dict
sort methods and lambda
s perhaps, but this is new territory for me, so I don't really have a clue.