PolarBear10
PolarBear10

Reputation: 2305

Compare list of list with dictionary

My list of list is

candidates= [[714, 1023, 768, 1078], [803, 938, 868, 995]]

My dictionary is:

main_dict = {(1561, 48, 1623, 105): [[[1592, 58]],
                                     [[1591, 59]],
                                     [[1585, 59]],
                                     [[1600, 58]]],

             (714, 1023, 768, 1078): [[[1, 5]],
                                      [[2, 6]],
                                      [[3, 3]],
                                      [[4, 3]]],

             (803, 938, 868, 995): [[[14, 5]],
                                    [[22, 64]],
                                    [[34, 31]],
                                    [[43, 32]]]

             }

I would like to have 2 lists, candidate_values_exists_in_dict_key which contains the corresponding values of candidates that exist in main_dict, and the other list contains the values that are in main_dict but not in candidate_values_exists_in_dict_key.

Here is what I tried, very cluttering and slow. Can someone have a faster way? Furthermore, how can I have an else statement that has the list of keys v which do not exist in candidate_values_exists_in_dict_key but in main_dict?

It is guaranteed that the candidates values will always be in the main_dict keys, and in the same order of appearance as the candidates.

candidate_values_exists_in_dict_key = []

values_of_main_dict_not_in_candidates_values_list=[] 

for x in candidates:
    for k, v in main_dict.items():
        if x == list(k):
            candidate_values_exists_in_dict_key.append(v)

Upvotes: 0

Views: 56

Answers (2)

alani
alani

Reputation: 13059

Given that you want to output a list of values that are not in the candidates in addition to a list of those that are, you are going to have to iterate through the dictionary in one form or another in any case.

Therefore the code in the question is basically fine. But you could improve it slightly by using a set of the candidates (converted to the tuples used as dictionary keys) to test inclusion, rather than having nested loops. Because you know that these are used as dictionary keys, you also know that they can be used as elements of a set.

candidate_tuples = set(map(tuple, candidates))

candidate_values_exists_in_dict_key = []
values_of_main_dict_not_in_candidates_values_list = [] 

for k, v in main_dict.items():
    if k in candidate_tuples:
        candidate_values_exists_in_dict_key.append(v)
    else:
        values_of_main_dict_not_in_candidates_values_list.append(v)

Upvotes: 0

Prem Anand
Prem Anand

Reputation: 2537

Just a normal list comprehension with dict lookup would do fine. There isn't any need for nested loops

candidate_values_exists_in_dict_key = [main_dict[tuple(c)] for c in candidates]

values_of_main_dict_not_in_candidates_values_list = [v for k,v in main_dict.items() if list(k) not in candidates]

Upvotes: 1

Related Questions