You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 is True. For each key in our target list, it compares the value from dict_a and dict_b.
  • If even one key's values don't match, all() returns False immediately. Only when all four pairs match does it return True.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 17:24:07