Heisenberg
Heisenberg

Reputation: 111

To reverse a dictionary and display values

I want to reverse a dictionary and display it in a specific format. Here is the sample input:

{'john':34.480, 'eva':88.5, 'alex':90.55, 'tim': 65.900} 

Output should be:

enter image description here

This is where I am with the code, but the problem is that it returns a list and not a dictionary.

CODE:

def formatted_print(my_dict):
    d = my_dict
    c = sorted(d.items(), cmp=lambda a,b: cmp(a[1], b[1]), reverse=True)
    return (c)

Upvotes: 1

Views: 199

Answers (4)

ohid
ohid

Reputation: 914

Simple code without importing any module or library :

def formatted_print(D):
    list_tuples=sorted(D.items(), key=lambda x: (-x[1], x[0]))

    for items in list_tuples:
        x="{0:10s}{1:6.2f}".format(items[0],items[1])
        print(x)

It prints:

alex       90.55
eva        88.50
tim        65.90
john       34.48

Upvotes: 1

timgeb
timgeb

Reputation: 78700

I want to sort it by values in descending order

The standard dictionary has arbitrary order. The only way to sort your dictionary is to sort the (key, value) pairs and build an OrderedDict from those:

>>> from collections import OrderedDict
>>> d = {'john':34.480, 'eva':88.5, 'alex':90.55, 'tim': 65.900} 
>>> od = OrderedDict(sorted(d.items(), key=lambda x: x[1], reverse=True))
>>> od
OrderedDict([('alex', 90.55), ('eva', 88.5), ('tim', 65.9), ('john', 34.48)])
>>> od['eva']
88.5

Printing:

>>> for name, value in od.items():
...     print name, value
... 
alex 90.55
eva 88.5
tim 65.9
john 34.48

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107297

If you want to print your items in a such order you don't need another dictionary, you can just loop over the sorted items and print the keys and values:

>>> d = {'john':34.480, 'eva':88.5, 'alex':90.55, 'tim': 65.900}
>>> for k, v in sorted(d.items(), key = itemgetter(1), reverse=True):
...     print k, '\t', v
... 
alex    90.55
eva     88.5
tim     65.9
john    34.48
>>> 

But if you want to preserve the items in a descending order, since dictionaries are not ordered data structures like lists you can use collections.OrderedDict in order to create an ordered dictionary:

>>> from collections import OrderedDict
>>> from operator import itemgetter
>>>
>>> D = OrderedDict(sorted(d.items(), key = itemgetter(1), reverse=True))
>>> 
>>> D
OrderedDict([('alex', 90.55), ('eva', 88.5), ('tim', 65.9), ('john', 34.48)])

Upvotes: 4

xiº
xiº

Reputation: 4687

import operator

x = {'john': 34.480, 'eva': 88.5, 'alex': 90.55, 'tim': 65.900}
res = sorted(x.items(), key=operator.itemgetter(1), reverse=True)
print res

>>> [('alex', 90.55), ('eva', 88.5), ('tim', 65.9), ('john', 34.48)]

That's what you are looking for. You could put it to OrderedDict().

Upvotes: 0

Related Questions