Assuming I've the following list of lists:
dict1 = [['Jeremy', 25, 120000], ['Paul', 23, 75000], ['Mike', 32, 80000]]
I can easily sort the lists on index 2 as follows:
from operator import itemgetter
sorted_dict = sorted(dict1, key=itemgetter(1))
print(sorted_dict)
>>>
[['Paul', 23, 75000], ['Jeremy', 25, 120000], ['Mike', 32, 80000]]
Things get a little more complicated with a dictionary of lists. Assuming I've the following:
dict2 = {'employee1':['Paul', 23, 75000],
'employee2':['Mike', 32, 80000],
'employee3':['Jeremy', 25, 120000]}
I can approximate a sort on index 2 as follows:
from operator import itemgetter
#First, extract lists
result1 = dict2.values()
#Second, sort list by index 2
result2 = sorted(result1, key=itemgetter(1))
#Finally, use for loop to sort dictionary
for a in result2:
for b in dict2.keys():
if a == dict2[b]:
print("{0}:{1}".format(b,a))
>>>
employee1:['Paul', 23, 75000]
employee3:['Jeremy', 25, 120000]
employee2:['Mike', 32, 80000]
I would like a better way to perform a sort on the dictionary. I found a community wiki post on sorting dictionaries (here) but the dictionary in that post has constant key. In my dictionary above, each list has a unique key.
Thanks.
Using Python 3.4.1