How can I check if the characters in a string are in a dictionary of values?

前端 未结 3 977
日久生厌
日久生厌 2021-01-16 02:14

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?

相关标签:
3条回答
  • 2021-01-16 02:36
    [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']
    
    0 讨论(0)
  • 2021-01-16 02:42
    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.

    0 讨论(0)
  • 2021-01-16 02:43

    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'}
    
    0 讨论(0)
提交回复
热议问题