如何在字典或字典中查找字符串是键还是值

时间:2019-03-15 00:19:55

标签: python dictionary

这看起来应该很简单,但是由于某些原因我无法到达那里。

我有一些可能采用多种格式的格言:

dict1 = {"repo": "val1", "org":"val2"}
dict2 = {"key1":"repo", "key2":"org"}
dict3 = {"key1":"org and stuff"}
dict4 = {"org and stuff":"value1"}
dict5 = {"key1":{"value1":"value2"}, "key2":{"1":"org"}}
dict6 = {"org":{"value1":"value2"}, "key2":{"value1":"value2"}}
dict7 = {"org":{"subkey1":{"value1":"value2"}}, "key2":{"value1":"value2"}}
dict8 = {"key1":{"subkey1":{"value1":"org"}}, "key2":{"value1":"value2"}}

我要搜索字符串'org',如果它在字典中的任何位置(键,值,键[subkey] [value]等),则返回true。我不希望部分字符串匹配。

也就是说,我正在寻找以下结果:

True
True
False
False
True
True
True
True

我已经阅读了这些问题,但是没有一个答案很正确,因为我可以嵌套字典:

How to search for all the characters from a string in all Dictionary.Values()

Generic Function to replace value of a key in a dict or nested dict or list of dicts

Find dictionary items whose key matches a substring

Filter a dict of dict

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

4 个答案:

答案 0 :(得分:5)

使用递归!

def indict(thedict, thestring):
    if thestring in thedict:
        return True
    for val in thedict.values():
        if isinstance(val, dict) and indict(val, thestring):
            return True
        elif isinstance(val, str) and val == thestring:
            return True
    return False

答案 1 :(得分:1)

技术上,您可以将dict转换为字符串,然后使用re搜索该单词是否存在。另外,如果您的决定非常大,则不需要循环,并且比使用循环/递归要快/简单。另外,如果您有子列表或元组等等

import re

def indict(data, word):
    return bool(re.search(f"'{word}'", str(data)))

为证明概念,请使用我测试过的命令,这将返回您想要的结果。

dicts = (dict1, dict2, dict3, dict4, dict5, dict6, dict7, dict8)

for d in dicts:
  print(indict(d, 'org'))

此打印:

True
True
False
False
True
True
True
True
True

答案 2 :(得分:0)

好像adrtam首先来到这里,但我基本上想到了同一件事

def searcher(input_dict, search_item):
    for key, value in input_dict.items():
        if search_item == key or search_item == value:
            return True
        elif type(value) is dict:
            searcher(input_dict[key], search_item) #search recursively
    return False

答案 3 :(得分:0)

如果搜索字符串在给定字典的任何键或值中,或者如果给定字典实际上不是字典,则可以使用递归函数返回True,如果搜索字符串是等于它:

def is_in(d, s):
    return s in d or any(is_in(v, s) for v in d.values()) if isinstance(d, dict) else d == s

这样:

for d in [
    {"repo": "val1", "org":"val2"},
    {"key1":"repo", "key2":"org"},
    {"key1":"org and stuff"},
    {"org and stuff":"value1"},
    {"key1":{"value1":"value2"}, "key2":{"1":"org"}},
    {"org":{"value1":"value2"}, "key2":{"value1":"value2"}},
    {"org":{"subkey1":{"value1":"value2"}}, "key2":{"value1":"value2"}},
    {"key1":{"subkey1":{"value1":"org"}}, "key2":{"value1":"value2"}}]:
    print(is_in(d, 'org'))

输出:

True
True
False
False
True
True
True
True