Search code examples
pythondictionaryformatted

How to sort numbers in strings in python


sorry... my English is not very good... so i didn't know How to ask this question... please just read so u can understand what i want... I have a def which takes a dictionary:

{'John':30.370, 'Mike':84.5, 'Sara':97.55, 'Frank': 75.990}

And i wanna return this:

Sara       97.55
Mike       84.50
Frank      75.99
John       30.37

But My solution don't return this! My solution:

def formatted(a):
    s=''
    for i in a:
        d='{0:<10s}{1:>6.2f}\n'.format(i, a[i])
        s=s+d
    s=s.rstrip()  
    return s
a={'John':30.370, 'Mike':84.5, 'Sara':97.55, 'Frank': 75.990}
print (formatted(a))

it returns:

John       30.37
Mike       84.50
Sara       97.55
Frank      75.99

I should sort these numbers...But i Have no idea How to do that! Anybody can help??


Solution

  • In one line :

    d = {'John': 30.370, 'Mike': 84.5, 'Sara': 97.55, 'Frank': 75.990}
    print(
        "\n".join(
            '{0:<10s}{1:>6.2f}'.format(k, v) for k, v in sorted(d.items(), key=lambda x: x[1], reverse=True)
        )
    )
    
    Sara       97.55
    Mike       84.50
    Frank      75.99
    John       30.37
    

    Explanation :

    • first, sort the dictionary according to the value : sorted(d.items(), key=lambda x: x[1], reverse=True) => sorted method in python
    • then, apply the format to all the sorted items => list comprehension
    • finally, use "\n".join() to regroup and format everybody in one string separated by \n => join method
    • at the end, everything is printed by the print() method