1

I want to check if the characters in any given string are listed in a dictionary of values (as keys) that i have created, how do I do this?

Rahul Sharma
  • 1,117
  • 3
  • 10
  • 12

3 Answers3

5

Use any or all depending on whether you want to check if any of the characters are in the dictionary, or all of them are. Here's some example code that assumes you want all:

>>> s='abcd'
>>> d={'a':1, 'b':2, 'c':3}
>>> all(c in d for c in s)
False

Alternatively you might want to get a set of the characters in your string that are also keys in your dictionary:

>>> set(s) & d.keys()
{'a', 'c', 'b'}
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1
string = "hello" 
dictionary = {1:"h", 2:"e", 3:"q"}
for c in string:
    if c in dictionary.values():
        print(c, "in dictionary.values!")

If you wanted to check if c is in the keys, use dictionary.keys() instead.

Benjamin Murphy
  • 108
  • 1
  • 8
0
[char for char in your_string if char in your_dict.keys()]

this will give you a list of all chars in your string that are present as keys in your dictionary.

Eg.

your_dict = {'o':1, 'd':2, 'x':3}
your_string = 'dog'
>>> [char for char in your_string if char in your_dict.keys()]
['d', 'o']
Pratik Mandrekar
  • 9,362
  • 4
  • 45
  • 65