Python新手求助:编写函数比较两字典指定键值对是否相等
Solution for Comparing Specific Dictionary Keys in Python
Hey there! As someone who's been in your shoes as a new Python learner, I can help you put together a simple, effective function for this task. Here's how to do it:
Basic Version (Works if you're sure the keys exist in both dicts)
This function focuses only on the four keys you care about and checks if their values match between the two dictionaries:
def compare_specific_keys(dict_a, dict_b): # List of keys we need to compare target_keys = ['start1', 'end1', 'start2', 'end2'] # Use `all()` to verify every key's value matches across both dicts return all(dict_a[key] == dict_b[key] for key in target_keys) # Test with your sample dictionaries A = {'id1': 'target', 'start1': '39', 'end1': '45', 'id2': 'query', 'start2': '98', 'end2': '104'} B = {'id1': 'target', 'start1': '39', 'end1': '45', 'id2': 'query', 'start2': '98', 'end2': '104'} print(compare_specific_keys(A, B)) # Output: True
Robust Version (Handles missing keys gracefully)
If you want to avoid unexpected KeyError cases (in case one of the dictionaries is missing a key), we can add a quick check first:
def compare_specific_keys(dict_a, dict_b): target_keys = ['start1', 'end1', 'start2', 'end2'] # Make sure both dicts have all the keys we need to compare if not all(key in dict_a and key in dict_b for key in target_keys): raise ValueError("Both dictionaries must contain all keys: start1, end1, start2, end2") # Now compare the values return all(dict_a[key] == dict_b[key] for key in target_keys)
How it works
- The
all()function checks that every condition in the generator expression isTrue. For each key in our target list, it compares the value fromdict_aanddict_b. - If even one key's values don't match,
all()returnsFalseimmediately. Only when all four pairs match does it returnTrue.
Hope this makes sense and solves your problem! Feel free to tweak it if you need to adjust for any edge cases you run into.
内容的提问来源于stack exchange,提问作者buji
相关产品推荐
相关产品推荐

