How to check if characters in a string are in a dictionary of values?

I want to check if the characters in any given string are specified in the dictionary of values ​​(like keys) that I created, how to do this?

0
source share
3 answers

Use anyor all, depending on whether you want to check if any of the characters are in the dictionary, or all of them. Here is a sample code that suggests what you want all:

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

Alternatively, you can get the character set in your string, which are also keys in your dictionary:

>>> set(s) & d.keys()
{'a', 'c', 'b'}
+2
source
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 want to check if c is in the keys, use dictionary.keys () instead.

0
source
[char for char in your_string if char in your_dict.keys()]

, .

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']
0

Source: https://habr.com/ru/post/1689482/


All Articles