compare dictionary with tuple and return the best matched element

Question:

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]}
Asked By: merkle

||

Answers:

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]
Answered By: 11574713
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.