简体   繁体   中英

sort tuples in dictionary based on time value

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM