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?
[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']
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.
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'}