sort tuples in dictionary based on time value

北战南征 提交于 2019-12-13 08:57:26

问题


I have a dictionary looking like this:

dict1 = {'key1': ['x1', [(time1,value1), (time3,value3), (time2,value2)]],
         'key2': ['x2', [(time6,value6), (time4,value4), (time5,value5)]],
          ...}

For each key in the dictionary, I wish to sort the tuples based on the time. Looking at the example above, assume that

time1 < time2 < time3
time4 < time5 < time6

The output I wish is then

dict1 = {'key1': ['x1', [(time1,value1), (time2,value2), (time3,value3)]],
         'key2': ['x2', [(time4,value4), (time5,value5), (time6,value6)]],
          ...}

The first value for each key 'x1', 'x2' .. etc are redundant and should (if anything) just be removed.

Can anyone help me with the issue of sorting the tuples in the dictionary based on the time value?

Thanks a lot in advance.


回答1:


You can just use a dict comprehension with sorted:

>>> {k: [v[0]] + [sorted(v[1])] for k, v in dict1.items()}
{'key1': ['x1', [('time1', 'value1'), ('time2', 'value2'), ('time3', 'value3')]],
 'key2': ['x2', [('time4', 'value4'), ('time5', 'value5'), ('time6', 'value6')]]}

If you want to drop the x value, you can simplify this to this:

>>> {k: sorted(v[1]) for k, v in dict1.items()}
{'key1': [('time1', 'value1'), ('time2', 'value2'), ('time3', 'value3')],
 'key2': [('time4', 'value4'), ('time5', 'value5'), ('time6', 'value6')]}

I'm using strings instead of actual times and values here, but provided that those time objects compare properly, the code will work the same. Using sorted, the list of tuples will just be sorted by the first elements in those tuples (or the second in case the firsts are equal, etc).



来源:https://stackoverflow.com/questions/46340751/sort-tuples-in-dictionary-based-on-time-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!