Last active
May 23, 2016 23:11
-
-
Save mesbahamin/1e3b6cd7714f1e133577ad4bd337f0a3 to your computer and use it in GitHub Desktop.
Searching a dict and ensuring either zero or one results.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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") |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found a perfect solution!