Matching key-value pairs

EasyDictionary Programs · 48 of 94

Write a Python program to find key-value pairs present in both dictionaries.

Advertisement
Input
{"k1": "p", "k2": "q", "k3": "r"}, {"k1": "p", "k2": "s"}
Output
k1: p is present in both a and b

Approach

  1. items() views support &.

Solution

Python
a = {"k1": "p", "k2": "q", "k3": "r"}b = {"k1": "p", "k2": "s"}for k, v in a.items() & b.items():    print(f"{k}: {v} is present in both a and b")
Output
k1: p is present in both a and b
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs