I want to search for a part of a string only from the values
(not keys
) from a dictionary in Python.
But the code I have is not able to search for the part of string which I got from a device output.
Here is the code
n = {'show run | i mpls ldp': '\rMon Jun 26 06:21:29.965 UTC\r\nBuilding configuration...\r\nmpls ldp'}
if "mpls ldp" in n:
print("yes")
else:
print("no")
Everytime when I run it always prints no
.
I want to search for mpls ldp
in the \nBuilding configuration...\r\nmpls ldp
value part.
You're currently inclusion checking the list of keys of the dictionary, rather than the values themselves. You can loop over the values to determine whether an entry contains the string in question:
To terminate after the first matching value has been found in the values, we can use a for-else
construction:
n = {
"show run | i mpls ldp": "\rMon Jun 26 06:21:29.965 UTC\r\nBuilding configuration...\r\nmpls ldp"
}
for value in n.values():
if "mpls ldp" in value:
print("yes")
break
else:
print("no")
yes
We can condense this to one line with a ternary conditional expression and a generator:
print ('yes' if any("mpls ldp" in value for value in n.values()) else 'no')
yes
any
also efficiently short-circuits.