简体   繁体   中英

check for specific key and value pairs in two dictionaries (both dictionary has same key and value pairs)

I have two dictionaries that have the same key and value pairs. I want to compare only the specific key-value pairs and return true. I am new to python, Please help me to write a function for the same.

The dictionaries are

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'}

Here I want to check if the 'start1' , 'end1' , 'start2' and 'end2' values are the same are not.

result = all( A[k]==B[k] for k in ('start1', 'end1', 'start2', 'end2'))

you can use a for loop:

wanted_keys = {'start1', 'end1', 'start2', 'end2'}

same = True
for k in wanted_keys:
    if A.get(k) != B.get(k):
        same = False
        break 

one line code:

all(A.get(k) == B.get(k) for k in wanted_keys)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM