IniMzungu
IniMzungu

Reputation: 97

Matching the values of one dictionary to the keys of another dictionary (Python)

Evening All,

Hope you are well.

My Objective I am trying to match the values of one dictionary to the keys of another.

dict1 has keys but no values dict2 has keys and values

dict2 has values that can be found as keys in dict1. I'm attempting to write code that identifies which values in dict2 match the keys in dict1.

My Attempt Commented code is below.

dict1 = {('dict1_key1',): [], ('dict1_key2',): []} #dictionary with keys, but no values;


for i in dict2.keys():  #iterate through the keys of dict2
    for x in dict2[i]:  #reaching every element in tuples in dict2
        if x == dict1.keys():  #if match found in the name of keys in dict1
            print(f"{i} holding {x}.") #print which key and value pair in dict 2 match the keys in dict1

The code works if I write the for loop as follows:


for i in dict2.keys():  #iterate through the keys of dict2
    for x in dict2[i]:  #reaching every element in tuples in dict2
        if x == dict1_key1 or x == dict1_key2():  #if match found in the name of keys in dict1
            print(f"{i} holding {x}.") #print which key and value pair in dict 2 match the keys in dict1

However, dict1 in reality needs to be able to contain an varying number of keys which is why I had hoped that if x == dict1.keys(): would work.

Any feedback would be greatly appreciated.

@Mark Meyer

Examples values as requested:

dict1 = {('Tower_001',): [], ('Tower_002'): []}

dict2 = {1: 'Block_A', 'Tower_001'] #first key in dict2
        #skipping keys 2 through 13
        {14: ['Block_N', 'Tower_002']#last key in dict2

Upvotes: 3

Views: 4346

Answers (1)

Mark
Mark

Reputation: 92440

You can make sets of all the value in the dict1.keys and dict2.value. Then just take the intersection of those sets to find keys that are also values:

dict1 = {('Tower_001',): [], ('Tower_005',): [], ('Tower_002',): []}

dict2 = {1: ['Block_A', 'Tower_001'], #first key in dict2
        14: ['Block_N', 'Tower_002']} #last key in dict2
         
         
set(k for l in dict2.values() for k in l) & set(k for l in dict1.keys() for k in l)
# {'Tower_001', 'Tower_002'}

Upvotes: 2

Related Questions