python,sorting,dictionary , How to sort for min/max from a dictionary of tuples?

## Question:

Tag: python,sorting,dictionary

src_type is a dictionary of tuples with the data structured as (start,end,frequency)

``````In [303]: src_type
Out[303]:
{'A': (440468754.0, 442213325.0, 25),
'B': (440448179.523912, 442202204.43813604, 285),
'C': (440447107.044571, 442268070.552849, 4914),
'D': (440448307.44081604, 442254145.172575, 443),
'E': (440458084.535652, 442253729.048885, 3060)}
``````

I would like to find the min of "start" and the max of "end"

These are my solutions:

# 1 (simple and crappy)

``````end_ts = 0
for i in src_type.values():
if end_ts < i[1]:
end_ts = i[1]
start_ts = end_ts

for i in src_type.values():
if start_ts > i[0]:
start_ts = i[0]
``````

# 2 (with some help from SO about sorting {})

``````b = src_type.items()
b.sort(key=lambda x:x[1][0])
min_start = b[0][1][0]
b.sort(key=lambda x:x[1][1])
max_end = b[-1][1][1]
``````

Is their a better an elegant solution ?

Answer:

I would use `min()` and `max()` with generator expressions:

``````In [6]: min(start for (start, end, frequency) in src_type.values())
Out[6]: 440447107.044571

In [7]: max(end for (start, end, frequency) in src_type.values())
Out[7]: 442268070.552849
``````

You could factor out `src_type.values()` if you like.

I chose to use symbolic names for `start`, `end` and `frequency` as to my eyes this improves the clarity of the code.

# Related:

## Javascript sort array of objects in reverse chronological order

javascript,arrays,sorting
I have an array of objects which holds a list of jobs and I would like to sort them in reverse chronological order as they would appear on a resume for example. I came up with the below solution which 'seems' to work but I was wondering if there is...

## sys.argv in a windows environment

python,windows,python-3.x
I'm attempting to learn python using the book 'a byte of python'. The code: import sys print('the command line arguments are:') for i in sys.argv: print(i) print('\n\nThe PYTHONPATH is', sys.path, '\n') outputs: the command line arguments are: C:/Users/user/PycharmProjects/helloWorld/module_using_sys.py The PYTHONPATH is ['C:\\Users\\user\\PycharmProjects\\helloWorld', 'C:\\Users\\user\\PycharmProjects\\helloWorld', 'C:\\Python34\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']...