Skip to content

Instantly share code, notes, and snippets.

@mesbahamin
Last active May 23, 2016 23:11
Show Gist options
  • Select an option

  • Save mesbahamin/1e3b6cd7714f1e133577ad4bd337f0a3 to your computer and use it in GitHub Desktop.

Select an option

Save mesbahamin/1e3b6cd7714f1e133577ad4bd337f0a3 to your computer and use it in GitHub Desktop.
Searching a dict and ensuring either zero or one results.
# This is a simplified version of a more complex problem I'm trying to solve.
# search() seems to have the desired behavior (see docstring), but seems a bit clumsy.
# Is there a more pythonic way to do this?
def search(my_list, my_dict, search_term):
"""Example Output:
---
>>> l = [1, 2, 3, 4]
>>> d = {1: "foo", 2: "bar", 3: "baz", 4: "baz"}
>>> search(l, d, "borkborkbork")
No results
>>> search(l, d, "foo")
1
>>> search(l, d, "baz")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 27, in search
ValueError: Shouldn't have more than one result
---
results should only ever have either 0 elements or 1 element.
this is because my_dict should have 1 to 1 correspondence between keys and values.
"""
results = [i for i in my_list if my_dict[i] == search_term]
if not results:
print("No results")
elif len(results) == 1:
print(results[0])
else:
raise ValueError("Shouldn't have more than one result")
@mesbahamin
Copy link
Author

mesbahamin commented May 23, 2016

Found a perfect solution!

def search(my_list, my_dict, search_term):
    try:
        [result] = [i for i in my_list if my_dict[i] == search_term] or [None]
    except ValueError as e:
        print("Duplicate values in 'my_dict'.")
        raise SystemExit
    else:
        if not result:
            print("No results")
        else:
            print(result)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment