Home > front end >  compare dictionary with tuple and return the best matched element
compare dictionary with tuple and return the best matched element

Time:08-04

I have a dictionary and I need to compare tuple with larger dictionary and get the best element based on the number of matches.

For example, below is my larger dictionary (d):

{('a', 'b', 'c', 'd', 'e', 'f'): [100, 101, 102],
 ('a', 'b', 'z', 'd'): [103, 104],
 ('a', 'b', 'x', 'd', 'e', 'f', 'g'): [105, 106, 107],
 ('a', 'b', 's', 'd', 'e'): [108],
 ('a', 'b', 'v', 'd', 'e', 'f', 'g', 'h'): [109, 110]}

below is my tuple:

x2 = ('a','b','c')

I need to compare my x2 with the larger dictionary. Here

('a', 'b', 'c', 'd', 'e', 'f'): [100, 101, 102]

matched because ('a','b','c') has 3 matches compared to other elements in the larger dictionary and I need to return this i.e;

('a', 'b', 'c', 'd', 'e', 'f'): [100, 101, 102]
matched: 3, value: [100,101,102]

How to achieve this? I am using the below code but it is not working

shared_items = {k: d[k] for k in x2 if k in d and d[k] == x2[k]}

CodePudding user response:

This goes through in multiple passes, looking for the first key that matches all 3 elements in the tuple, otherwise, the first 2 in the tuple, etc.

small_key = ('a','b','c')
for small_key_size in range(len(small_key), 0, -1):
    for big_key in d:
        if big_key[:small_key_size] == small_key:
            print(f"matched: {small_key_size}, value: {d[big_key]}")
            break

(edited, had loops inside out)

Outputs

matched: 3, value: [100, 101, 102]
  • Related