Search code examples
pythonpython-3.xdictionaryrangeminimum

Looking for minimum between a range of index in a dictionary python


I am looking for minimum between a range of index in a dictionary; for instance:

A = {1: -3, 2: -5, 3: 4, 5: 12, -34: 23, 64: 32}

I want to find:

min(A[2..5]) = min(A[2] A[3] A[4]A [5]) = -5

Is this possible?


Solution

  • Python list does not support indexing via a list of indexers. There are a couple of solutions to overcome this.

    Where you know keys exist

    You can use itemgetter and sequence unpacking:

    from operator import itemgetter
    
    A = {1: -3, 2: -5, 3: 4, 5: 12, -34: 23, 64: 32}
    
    res = min(itemgetter(*[2, 3, 5])(A))
    
    # -5
    

    Where keys may not exist

    You can use a range object to specify a range of keys. A list or set would work too. Here we feed a generator expression to min:

    res = min(v for k, v in A.items() if k in range(2, 6))
    
    # -5