I have a dict
that has string-type keys whose exact values I can't know (because they're generated dynamically elsewhere). However, I know that that the key I want contains a particular substring, and that a single key with this substring is definitely in the dict.
What's the best, or "most pythonic" way to retrieve the value for this key?
I thought of two strategies, but both irk me:
for k,v in some_dict.items():
if 'substring' in k:
value = v
break
-- OR --
value = [v for (k,v) in some_dict.items() if 'substring' in k][0]
The first method is bulky and somewhat ugly, while the second is cleaner, but the extra step of indexing into the list comprehension (the [0]
) irks me. Is there a better way to express the second version, or a more concise way to write the first?
k.startswith('substring')
ork.endswith('substring')
if it's at the beginning or end; they may be faster.some_dict
for then it's entirely useless and a list would be better. If you have a list of substrings you want to match you'll have a time complexity of O(N**2). You'd need a index over the keys to do this efficiently though, full text search engines like Sphinx do that basically.first method is bulky and somewhat ugly, while the second is cleaner
small comment here: second is not cleaner, it just has less\n
characters. There is some strange belief that single-liners work faster and are more readable. They are not.