karthik
karthik

Reputation: 192

check substring exists in a dictionary value during iteration

Below code is working fine , but can anyone guide how to simplify this. newrelicid is a dictionary where it contains 'number' as key and 'some string' as value (string can contain substrings like prod,test,local etc ) Basically I am trying to ignore the values ( j ) that contains substring from the list ['dev','staging','qat','uat','local','eu']

sample newrelicid value

{1: 'Service PROD', 2: 'service', 3: 'guess-service (Production)', 4: 'check-service (Dev)', 5: 'analytics-service (Staging)' }

loop:

for i,j in newrelicid.items():
  if 'staging' not in j.lower() and not 'qat' in j.lower() and not 'uat' in j.lower() and not 'local' in j.lower() and not 'eu' in j.lower() and not 'dev' in j.lower():
    print(j)    

Upvotes: 1

Views: 40

Answers (3)

Brad Solomon
Brad Solomon

Reputation: 40878

You can use any() to effectively mimic a nested iteration:

>>> newrelicid = {
...     1: 'Service PROD',
...     2: 'service',
...     3: 'guess-service (Production)',
...     4: 'check-service (Dev)',
...     5: 'analytics-service (Staging)'
... }
>>> blacklist = {'dev','staging','qat','uat','local','eu'}

>>> {v for v in newrelicid.values()
...     if not any(i in v.casefold() for i in blacklist)}
{'Service PROD', 'guess-service (Production)', 'service'}

This produces a set[str] of the passed values.

Upvotes: 2

MarcoP
MarcoP

Reputation: 1776

It seems you want to apply a filter.

By the way, since you are only looking at the strings in your dictionaty, use dict.values()

l = ['staging','qat', 'uat', 'local', 'eu', 'dev']

list(filter(lambda x : not any(e in x.lower() for e in l),  newrelicid.values()))

['Service PROD', 'service', 'guess-service (Production)']

Upvotes: 1

Alain T.
Alain T.

Reputation: 42143

You could use a regular expression:

import re

pattern = r'staging|local|uat|qat|dev|eu' # one pattern for all keywords

newrelicid = {1: 'Service PROD', 2: 'service', 3: 'guess-service (Production)',
              4: 'check-service (Dev)', 5: 'analytics-service (Staging)' }

for j in newrelicid.values():
    if re.search(pattern,j.lower()): # match with lowercase
        print(j)

check-service (Dev)
analytics-service (Staging)

You could improve the pattern if what you need are whole words and not merely substrings:

pattern = r'\b(staging|local|uat|qat|dev|eu)\b'

Upvotes: 1

Related Questions