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

Searching dictionary of tuple lists

Still learning Python data structures so please bear with me. I have a dictionary of lists of two-tuples:

ex_dict = {4: [(6, 3), (5, 1), (7, 5)], 
           6: [(4, 3), (7, 2), (0, 5)], 
           7: [(6, 2), (5, 2), (4, 5)], 
           3: [(2, 2), (5, 9), (1, 2)], 
           2: [(3, 2)], 
           5: [(7, 2), (4, 1), (3, 9)], 
           1: [(3, 2), (0, 3)], 
           0: [[1, 3], [6, 5]]}

I want to access the second element of a tuple. For example, suppose I have u=3 as the key value and v=5 as the first tuple value. How do I access the 9 in the key=3 tuple list?

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

>Solution :

You can use a for loop to loop over the list of tuples:

u = 3
v = 5
result = None
for fst, snd in ex_dict[u]:
    if fst == v:
        result = snd
        break
    
print(result)

This outputs:

9

If you have a lot of queries to make, it would be better to transform the values from lists of tuples into dictionaries. The syntax is a bit cleaner, and lookups will be faster:

u = 3
v = 5
reshaped_dict = {
    k: {fst: snd for fst, snd in v} for k, v in ex_dict.items()
}

result = reshaped_dict[u][v]
print(result)

This also outputs:

9
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