0

I'm learning python and in need of some tips working with dictionaries. Please see code below. I've tried using if word in filename.values() and if filename[word] to check if the word exists inside the dictionary but it's not working. I want to check and if possible count the total number of times word appears inside of those lists inside the dictionary. Please advise!

files = {"f1": ["cat", "dog", "mouse"],
         "f2": ["rat", "elephant", "tiger"]}

word = "dog"

for filename in files:
    if word in filename.values():
        print(True)
    else:
        print(False)
  • 1
    Does this answer your question? [Counting the Number of keywords in a dictionary in python](https://stackoverflow.com/questions/2212433/counting-the-number-of-keywords-in-a-dictionary-in-python) – Software2 Dec 29 '20 at 08:49
  • `for filename in files` will iterate over the dictionary's keys. You need `files.items()` for `key,value` pairs – yatu Dec 29 '20 at 08:50
  • No, because it's only counting the keys of the dictionary. –  Dec 29 '20 at 08:50
  • `for key, value in files.items(): if word in value: print(True) else: print(False)` – dudulu Dec 29 '20 at 08:51
  • `any(word in i for i in files.values())` to check if is in any of the lists. – Klaus D. Dec 29 '20 at 08:52

1 Answers1

0

It is what you expected?

files = {"f1": ["cat", "dog", "mouse"],
         "f2": ["rat", "elephant", "tiger", "dog"]}

word = "dog"
counter = 0

for values in files.values():
    if word in values:
        print(True)
        counter +=1
    else:
        print(False)

print(counter)
rozumir
  • 845
  • 9
  • 20