-6

Say I've got a file with multiple names and integers like so:

name1:5
name2:3
name3:10

How can I add this to a dictionary, and then print it in descending order (eg highest value to lowest value)

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Max Vapton
  • 29
  • 5
  • See http://stackoverflow.com/questions/22841419/python-object-list-sort-in-descending-order-based-on-object-attribute –  Jul 28 '15 at 19:42

3 Answers3

1

Assuming by list you meant dict, this is what you want:

 names={'name1':5, 'name2':3, 'name3':10}
 print sorted(names, key=lambda x:names[x], reverse=True)

As another poster pointed out, the original poster requested to print out both the name & it's value. To accomplish this, change the code to:

 names={'name1':5, 'name2':3, 'name3':10}
 for name in sorted(names, key=lambda x:names[x], reverse=True):
     print name, names[name]
user590028
  • 11,364
  • 3
  • 40
  • 57
  • This would give you a list of sorted keys if it were a dict – Padraic Cunningham Jul 28 '15 at 19:49
  • OP just wanted to print out list of names in descending order. – user590028 Jul 28 '15 at 19:50
  • OP wants `[name3:10, name1:5, name2:3]` as the output, if it is a dict then you would have to sort the items and then use an OrderedDict to output as a dict in sorted order – Padraic Cunningham Jul 28 '15 at 19:55
  • I assumed his "real" problem was not understanding the difference between `list` and `dict` types, so I demonstrated how to correctly handle the data type. I assumed once he saw that would lead him to what he actually wanted -- but for completeness, I have finished the code as you suggested. – user590028 Jul 28 '15 at 20:00
0

You need to specify an appropriate key function for the builtin sorted:

# I assume this is what your input looks like
input = ["name1:5", "name2:3", "name3:10"]
output = sorted(input, key=lambda x: int(x.split(":")[1]), reverse=True)
chepner
  • 497,756
  • 71
  • 530
  • 681
-1

i got your point what you are saying and how it is done is given below :)

a=[name1:5, name2:3, name3:10]
def Last(s):
   return s[-1]
sorted(a, key=Last)

and then in this way you can sort it in reverse ..as per your choice ..enjoy :)

Ravi Rathore
  • 101
  • 1
  • 11