aletede91
aletede91

Reputation: 1166

How do I iterate over two lists of dictionaries to find a common key-value pair?

I have two lists that, each containing a couple of dictionaries: How could I check if there is a common key-value pair in both dictionaries ?

Example list of dictionaries - 1

[
    {
        'id':'1',
        'name':'a'
    },
    {
        'id':'2',
        'name':'c'
    }
]

Example list of dictionaries - 2

[
    {
        'id':'4',
        'name':'d'
    },
    {
        'id':'2',
        'name':'a'
    }
]

In the above example, there is a common key-value pair: 'name':'a'

How can I check if a similar match exists ?

Upvotes: 0

Views: 62

Answers (1)

ooa
ooa

Reputation: 475

len(
    set.intersection(
        {x["name"] for x in list_1},
        {x["name"] for x in list_2},
    )
) > 0

...assuming you have the lists assigned to variables list_1 and list_2.

Upvotes: 4

Related Questions