0

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??

3 Answers3

1
>>> d = {'John':30.370, 'Mike':84.5, 'Sara':97.55, 'Frank': 75.990}
>>> b = sorted(d.items(), key=lambda x: x[1])
>>> print b
[('John', 30.37), ('Frank', 75.99), ('Mike', 84.5), ('Sara', 97.55)] 

for reverse

>>> c = sorted(d.items(), key=lambda x: x[1] ,reverse=True)
>>> print c
[('Sara', 97.55), ('Mike', 84.5), ('Frank', 75.99), ('John', 30.37)]

for print use :

d = collections.OrderedDict(dict(c)) # c is upder dict
for i, v in d.items(): 
    _dict_pair='{0:<10s}{1:>6.2f}\n'.format(i, v)
    print(_dict_pair)
Kallz
  • 2,515
  • 1
  • 18
  • 36
0

You need to sort the dictionary on values using sorted and [operator.itemgetter][1].

In [100]: _dict = collections.OrderedDict(sorted(d.items(), key=operator.itemgetter(1), reverse=True)) # d is your dictinory
    
In [101]: _dict
Out[101]: 
OrderedDict([('Sara', 97.55),
             ('Mike', 84.5),
             ('Frank', 75.99),
             ('John', 30.37)])

Then you need to use collections.OrderedDict as dictionaries are hash key pair.

for i, v in _dict.items():
       d='{0:<10s}{1:>6.2f}\n'.format(i, v)
       print(d)

Sara 97.55

Mike 84.50

Frank 75.99

John 30.37

Community
  • 1
  • 1
Vishnu Upadhyay
  • 4,813
  • 1
  • 11
  • 26
0

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
Cédric Julien
  • 69,378
  • 13
  • 112
  • 121