Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.")
        break
else:
    print("Input is the highest.")

Returns correctly:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.")
else:
  print("Input is the highest.")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading