简体   繁体   English

如何检查字符串中的字符是否在值字典中?

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

我想检查任何给定字符串中的字符是否列在我创建的值字典(作为键)中,我该怎么做?

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. 使用anyall具体取决于您是否要检查字典中是否有任何字符,或者所有字符都在字典中。 Here's some example code that assumes you want all : 这是一些假设您想要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'}
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. 如果要检查键是否在c中,请改用dictionary.keys()。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 字典我如何将值更改为字符串 - Dictionary how can i change values to string 如何循环字符串中的字符并检查它是否在字典python中 - How to loop characters in string and check if it is in dictionary python 如何检查列表中的字典中是否存在某种值组合? - How can I check if a certain combination of values exists in a dictionary in a list? 当我使用 function eval(String dictionary) -> dictionary PYTHON 时,如何处理字典中的缺失值? - How can I handle missing values in the dictionary when I use the function eval(String dictionary) -> dictionary PYTHON? "<i>How can I check if a string has the same characters?<\/i>如何检查字符串是否具有相同的字符?<\/b> <i>Python<\/i> Python<\/b>" - How can I check if a string has the same characters? Python 如何检查字典是否包含字典? - How can I check if a dictionary contains a dictionary? 我可以一次检查字典中的所有值吗? - Can I check all the values in a dictionary at once? 当我只能访问该字典的字符串值时,如何从字典中调用.format()? - How can I call .format() from a dictionary when I can only access the string values of that dictionary? 如何检查字符串中的特定字符? - How can you check for specific characters in a string? 如何从所有Dictionary.Values()中的字符串中搜索所有字符 - How to search for all the characters from a string in all Dictionary.Values()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM