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

前端 未结 3 1007
日久生厌
日久生厌 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']
    

提交回复
热议问题