pythondictionarydictionary-comprehension

Value from one dictionary matches key of another dictionary


I want to patch a record, but I need to verify whether it will update. Otherwise, I get an HTTP 403 error.

How do I return the patch dictionary when the verification is true?

Verification has two parts:

  1. patch_dict['equip_id] is in verify_dict.keys()
  2. verify_dict value has a valid_str
valid_str = ['Not', 'Unique']
patch1_dict = {'id': 123, 'equip_id': 100}
patch2_dict = {'id': 123, 'equip_id': 150}
verify_dict = {'id':123, 'equip_150': 'From Template', 'equip_100': 'Unique'}

patch1_dict passes verification, but patch2_dict will not.

My attempt of creating the dictionary comprehension:

{k:v for (k, v) in patch1_dict.items() if v in verify_dict for sub_v in valid_str}

Solution

  • There's no need for a loop. You need to construct the appropriate key in verify_dict from the value of equip_id in patch_dict.

    def verify(patch_dict, verify_dict, valid_str):
        equip_key = f'equip_{patch_dict["equip_id"]}'
        return patch_dict['id'] == verify_dict['id'] and verify_dict.get(equip_key) in valid_str
    
    valid_str = ['Not', 'Unique']
    patch1_dict = {'id': 123, 'equip_id': 100}
    patch2_dict = {'id': 123, 'equip_id': 150}
    verify_dict = {'id':123, 'equip_150': 'From Template', 'equip_100': 'Unique'}
    
    print(verify(patch1_dict, verify_dict, valid_str)) # True
    print(verify(patch2_dict, verify_dict, valid_str)) # False