Ad

How Sorted A Dictionary In Ascending Order Using Python?

I have this dictionary:

pen_dict = [('temp', [2500, 2500, 2450, 2450, 2500, 2500, 2350, 2450, 2400, 2450, 2450, 2400, 2500]), ('id', [3, 7, 12, 10, 8, 2, 1, 4, 11, 5, 13, 6, 9])]

But I need to order in this way in the OUTPUT:

[('id', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ,12, 13]), ('temp', [2350, 2500, 2500, 2450, 2450, 2400, 2500, 2500, 2500, 2450, 2400, 2450, 2450])]

The value in 'temp' and 'id' are linked

Ad

Answer

Here's one way to implement this.

dic = {'temp': [2500, 2500, 2450, 2450, 2500, 2500, 2350, 2450, 2400, 2450, 2450, 2400, 2500], 
       'id': [3, 7, 12, 10, 8, 2, 1, 4, 11, 5, 13, 6, 9]}
dic['id'],dic['temp'] = map(list,zip(*sorted(zip(dic['id'],dic['temp']))))

The resulting dictionary:

{'temp': [2350, 2500, 2500, 2450, 2450, 2400, 2500, 2500, 2500, 2450, 2400, 2450, 2450], 
    'id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]}
Ad
source: stackoverflow.com
Ad