Marty Wallace
Marty Wallace

Reputation: 35744

Find specific dictionary element without looping

Is there a way in python to check if any dictionary element has a specific value at a specific key, without looping over the entire dictionary?

So, in the following example:

 [{
        "ID": "1",
        "Name": "Bob",
    },
    {
        "Id": "2",
        "Name": "Dave",
    },
    {
        "Id": "3",
        "Name": "Dave",
    }]

I would like to get a true/false answer if any there are any elements with the name 'Dave'

Upvotes: 1

Views: 247

Answers (2)

Blender
Blender

Reputation: 298226

Your data structure doesn't support O(1) lookups, so you still have to loop through it:

any(d['Name'] == 'Dave' for d in dicts)

Passing a generator into any lets it short-circuit, so it'll stop once an element is found.

If you need to do this often, you can combine all of the items into a single lookup table:

from collections import defaultdict

total = defaultdict(set)

for d in dicts:
    for key, value in d.items():
        total[key].add(value)

Now, you can do O(1) lookups:

'Dave' in total['Name']

Upvotes: 7

Rushy Panchal
Rushy Panchal

Reputation: 17532

Try this: "Dave" in d.values() where d is your dictionary.

Since you have a list of dictionaries, try:

any(d.get("Name") == "Dave" for d in my_dicts). If one of the dictionaries doesn't have the key "Name", it will be handled (it returns None and None != "Dave").

Upvotes: 1

Related Questions