python - Sorting dictionary containing lists -


assuming i've following list of lists:

dict1 = [['jeremy', 25, 120000], ['paul', 23, 75000], ['mike', 32, 80000]] 

i can easily sort lists on index 2 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 little more complicated dictionary of lists. assuming i've following:

dict2 = {'employee1':['paul', 23, 75000],           'employee2':['mike', 32, 80000],           'employee3':['jeremy', 25, 120000]} 

i can approximate sort on index 2 follows:

from operator import itemgetter  #first, extract lists result1 = dict2.values() #second, sort list index 2 result2 = sorted(result1, key=itemgetter(1)) #finally, use loop sort dictionary in result2:     b in dict2.keys():         if == dict2[b]:             print("{0}:{1}".format(b,a))  >>>    employee1:['paul', 23, 75000]    employee3:['jeremy', 25, 120000]    employee2:['mike', 32, 80000] 

i better way perform sort on dictionary. found community wiki post on sorting dictionaries (here) dictionary in post has constant key. in dictionary above, each list has unique key.

thanks.

using python 3.4.1

first, can't sort dict because doesn't have order 1. can sort it's items however:

sorted(d.items(), key=lambda t: t[1][1]) 

should trick.

notes

  • t[1] # => "value", t[0] "key"
  • t[1][1] # => second element in value.

you'll list of 2-tuples (where first element key, , second element value). of course, pass list of 2-tuples directly collections.ordereddict if wanted construct dict has ordering after fact ...

1more correctly, order arbitrary , change based on key insertions, deletions, python implementation or version ... (which why it's easier dict's unordered)


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -