0

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.

Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
mac
  • 863
  • 3
  • 21
  • 42

1 Answers1

2

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.

Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
  • Your solution print 'yes' or 'no' many times. You need add flag and break if you need fast stop ``` for value in n.values(): if substring in value: found = True break if found: print("Yes, the substring is present in the dictionary values.") else: print("No, the substring is not found in the dictionary values.") ``` – Vlad Jul 15 '23 at 08:59
  • I added "fast stop" with a for-else, looks good to you? – Sebastian Wozny Jul 15 '23 at 09:03