Lists stored as values in a dictionary of variable length – how to access all the last list items?

What is the most efficient way to access all the last list items of lists stored in a dictionary? Please note that I am looking for a solution that works independently of the numbers of items in the dictionary.

As an example, here I would like to check if a number is higher than any of the last items in the lists. I think I got a solution but it seems convoluted and I am wondering if there is a better way.

input_num = 5

lst_dct = {
    "lstA": [5, 12, 3, 4],
    "lstB": [2, 3, 7, 11],
    "lstC": [3, 8, 2, 20]

for key, value in lst_dct.items():
    if input_num < value[-1]:
        print("Input is **not** the highest.")
    print("Input is the highest.")

Returns correctly:

Input is **not** the highest. 

>Solution :

You are pretty close to optimal. You can replace the items() call with values() to save an unpacking and also shorten the code a bit, but that’s it.

if any(value[-1] >= input_num  for value in lst_dct.values()):
  print("Input is **not** the highest.")
  print("Input is the highest.")

Leave a Reply