根据时间值对字典中的元组进行排序
我有一本这样的字典:
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
那么我希望的输出是
dict1 = {'key1': ['x1', [(time1,value1), (time2,value2), (time3,value3)]],
'key2': ['x2', [(time4,value4), (time5,value5), (time6,value6)]],
...}
每个键"x1","x2" ..等的第一个值都是多余的,应该删除(如果有的话).
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?
非常感谢.
您可以对sorted
使用dict理解:
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')]]}
如果要删除x
值,可以将此简化为:
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')]}
我在这里使用字符串而不是实际的时间和值,但前提是这些时间对象可以正确比较,所以代码也可以一样.使用sorted
,将仅按这些元组中的第一个元素对元组列表进行排序(如果第一个相等,则按第二个元素进行排序,依此类推).
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).