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)
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)
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]
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)
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 :)