Home > other >  How to check if a value is in a dictionary one by one
How to check if a value is in a dictionary one by one

Time:05-11

I'm brand new to coding so I'm sure this is a very simple question, but here's my code:

d = {'1': 'my', '3': 'is', '2': 'name', '5': 'johnny', '4': 'appleseed'}
phrase = ('my', 'nme', 'es', 'johnny', 'appleseed')

for i in range(1,len(phrase)):
    if phrase not in d.values():
        print("Typo")
    else:
        print("No typo")

What I'm trying to do is check each string one by one to see if it's present in the dictionary "d". If it's present, I want to print "No Typo" and if it's not, I want to print "Typo". Thank you!

CodePudding user response:

An advice, avoid repeatedly using x in d.values() as the average complexity is O(n).

Initialize a set to have a O(1) search:

d = {'1': 'my', '3': 'is', '2': 'name', '5': 'johnny', '4': 'appleseed'}
phrase = ('my', 'nme', 'es', 'johnny', 'appleseed')

S = set(d.values())
for w in phrase:
    if w not in S:
        print(f"{w}: Typo")
    else:
        print(f"{w}: No typo")

example (repeated values):

d = {'1': 'my', '3': 'is', '2': 'name', '5': 'johnny', '4': 'appleseed'}
d = dict(enumerate(list(d.values())*100000))
phrase = ('my', 'nme', 'es', 'johnny', 'appleseed')*1000

%%timeit
S = set(d.values())
for w in phrase:
    w not in S
3.35 ms ± 51.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
for w in phrase:
    w not in d.values()
13.3 s ± 76.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

example 2 (unique values):

d = {'1': 'my', '3': 'is', '2': 'name', '5': 'johnny', '4': 'appleseed'}
d = dict(enumerate(range(1000000)))
phrase = (0,1,2,3,-1,-2)*1000

%%timeit
S = set(d.values())
for w in phrase:
    w not in S
30.1 ms ± 1.42 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
for w in phrase:
    w not in d.values()
# sill running after 1min

CodePudding user response:

d = {'1': 'my', '3': 'is', '2': 'name', '5': 'johnny', '4': 'appleseed'}
phrase = ('my', 'nme', 'es', 'johnny', 'appleseed')

for i in phrase:
    if i not in d.values():
        print(f"{i} → Typo")
    else:
        print(f"{i} → No typo")

OUTPUT

my → No typo
nme → Typo
es → Typo
johnny → No typo
appleseed → No typo
  • Related