Home > Net >  Searching dictionary of tuple lists
Searching dictionary of tuple lists

Time:05-13

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?

CodePudding user response:

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
  • Related