Python 如果嵌套字典值中存在子字符串,是否返回父字典?
如何在嵌套的somedict中搜索子字符串“钢铁侠”后才返回“key_三”。目标是如果找到Python 如果嵌套字典值中存在子字符串,是否返回父字典?,python,dictionary,search,substring,Python,Dictionary,Search,Substring,如何在嵌套的somedict中搜索子字符串“钢铁侠”后才返回“key_三”。目标是如果找到“钢铁侠”,则返回“key\u three”[key][dictionary have->**]的所有父字典类型值,即包括key\u three\u one:[值]、key\u three\u two:[值]和第三个dictionary元素{/strong> somedict = [ { "anyKey":1,
“钢铁侠”
,则返回“key\u three”[key][dictionary have->**]的所有父字典类型值,即包括key\u three\u one:[值]、key\u three\u two:[值]
和第三个dictionary元素{/strong>
somedict = [
{
"anyKey":1,
"key_two":2,
**{ #key_three/value of key_three is nothing but a dictionary.
key_three_one: "spiderman",
key_three_two:"superman",
"key_three_three":{
"from_asguard" : "is not Iron Man:batman"
}
}**
}]
我已经浏览了以下链接:
1.
2.
3.
4. . 在您的
somedict
列表中遍历字典中的项
for key,value in somedict[0].items():
if 'Iron Man' in str(value):
print(key, value)
>>>key_three {'inside_key_three': {'from_asguard': 'is not Iron Man'}}
或者您可以使用列表理解:
[{k:v} for k,v in somedict[0].items() if 'Iron Man' in str(v)]
>>>[{'key_three': {'inside_key_three': {'from_asguard': 'is not Iron Man'}}}]
所以访问所有的链接,你一定写了一些代码。你能分享一下你的努力吗,看看你是否试图自己找到一个解决方案。
code
n=len(somedict)
x=0 y=0 35;对于范围(n)中的x:#x+=1对于somedict[:]中的每个值:x+=1#打印(每个值)对于键,每个值[0]中的值。items():#打印(键,值)如果str(value)中的“钢铁侠”:print(value)y+=1 print(“\n\n\n”,x)print(“\n\n,y)
忽略x和YDo请不要对代码使用注释。改为编辑您的问题。理想情况下,你的问题应该是独立的,因此包含回答你问题所需的所有信息。这有帮助,但不是我所期望的,仍然在寻找答案。