首页 > 解决方案 > Python - Sorting values in a dict of lists

问题描述

A set of 13 sensors transmit numerical data that is read every 5 minutes. To capture these values I used a dictionary of lists:

Sensors = {
         'Sensor1':[10.52,12.45,15.70],
         'Sensor5':[12.32,22.80,30.42],
         'Sensor3':[4.7,3.4,2.1],
         'Sensor8':[2.34,4.28,7.10],
         'Sensor4':[10.64,14.76,4.25],
         'Sensor2':[3.21,7.88,9.22],
         'Sensor6':[4.11,9.32,2.70],
         'Sensor9':[11.45,14.72,8.30],
         'Sensor7':[6.10,3.98,10.66],
         'Sensor10':[7.22,8.67,10.99],
         'Sensor13':[1.19,4.65,0.87],
         'Sensor12':[2.10,5.46,3.21],
         'Sensor11':[5.80,8.22,14.39]
         }

I need to sort this list so that the sensors that have had a positive increase appear at the top. To achieve this goal, I created another dictionary DeltaValues with the name of the sensor and the difference between the last and the first value captured:

 DeltaValues={}
  for x, y in Sensors.items():
      if len(y) > 1:
         DeltaValues[x] = format(y[-1] - y[0],'.2f')
      else:
         DeltaValues[x] = format(y[0],'.2f')

I used this syntax to sort:

sorted_d = {k: v for k, v in sorted(DeltaValues.items(), key=lambda x: x[1])}

But the result was not what I expected:

print(sorted_d)

{'Sensor13': '-0.32',
 'Sensor6': '-1.41',
 'Sensor3': '-2.60',
 'Sensor9': '-3.15',
 'Sensor4': '-6.39',
 'Sensor12': '1.11',
 'Sensor5': '18.10',
 'Sensor10': '3.77',
 'Sensor7': '4.56',
 'Sensor8': '4.76',
 'Sensor1': '5.18',
 'Sensor2': '6.01',
 'Sensor11': '8.59'}

标签: pythonlistsortingdictionary

解决方案


Dicts do not guarantee to return the values in order in which they were put in.

Consider ordered dict. https://docs.python.org/3/library/collections.html#collections.OrderedDict


推荐阅读