看起来应该很简单,但是由于某种原因我无法到达那里。
我有可能是几种可能的格式的字典:
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"}}
Run Code Online (Sandbox Code Playgroud)
我要搜索字符串'org',如果它在字典中的任何位置(键,值,键[subkey] [值]等),则返回true。我不希望部分字符串匹配。
也就是说,我正在寻找以下结果:
True
True
False
False
True
True
True
True
Run Code Online (Sandbox Code Playgroud)
我已经阅读了这些问题,但是没有一个答案很正确,因为我可能嵌套了一些字典:
使用递归!
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55 次 |
| 最近记录: |