簡體   English   中英

如何在字典或字典的字典中查找字符串是鍵還是值

[英]How to find whether a string either a key or a value in a dict or in a dict of dicts

這看起來應該很簡單,但由於某種原因我無法到達那里。

我有幾種可能的格式的字典:

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' ,如果它在字典中的任何位置(鍵、值、鍵 [子鍵] [值] 等),則返回 true。 我不想要部分字符串匹配。

也就是說,我正在尋找以下結果:

True
True
False
False
True
True
True
True

我已經閱讀了這些問題,但沒有一個能完全回答,因為我可以嵌套字典:

如何從所有 Dictionary.Values() 中的字符串中搜索所有字符

通用 Function 替換字典或嵌套字典或字典列表中的鍵值

查找鍵與 substring 匹配的字典項

過濾dict的dict

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

使用遞歸!

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

從技術上講,您可以將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

好像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

遞歸是一個不錯的選擇。 遍歷字典的鍵和值,尋找目標字符串並遞歸我們一路上找到的任何嵌套字典值:

def in_nested_dict(needle, haystack):
    if isinstance(haystack, dict):
        return any(
            k == needle or v == needle or in_nested_dict(needle, v)
            for k, v in haystack.items()
        )
    return False


if __name__ == "__main__":
    tests = [
        {"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"}},
    ]

    for test in tests:
        print(in_nested_dict("org", test))

Output:

True
True
False
False
True
True
True
True

如果搜索字符串在給定字典的任何鍵或值中,或者如果給定字典實際上不是字典,則可以使用遞歸函數返回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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM