![](/img/trans.png)
[英]Python, iterate through multiple lists in a dictionary object to find a specific value
[英]Iterate through nested Dictionary Object and get the value of specific object in Python
我想從這個字典中獲取所有ObjectId的值,它是列表和字典的組合。 我需要的答案是 -> 2, 2, [[ "Value is 1"], ""], 3, 2
我獲取 ObjectId 的解決方案。 這只是給了我內部 ObjectId 的值。 想要獲取所有 ObjectId 的值,無論值是 int 還是 list 等。
for key in dictObj:
if key == "RESULT":
if (type(dictObj[key])== list):
for list in dictObj[key]:
for key,value in list.items():
while(True):
if (type(value)==dict) and value:
for key1,value1 in value.items():
value = value1
key = key1
elif (key=="ObjectId"):
print(value)
break
else:
break
字典對象是
dictObj = {
"Id": 1,
"RESULT": [
{
"Check": {
"checkinstance": {
"ObjectId": 2,
"Class": "Base"
}
},
"Class": "Base"
},
{
"ObjectId": 2,
"Class": "Base",
"Start": {}
},
{
"Display": {
"part": {
"Class": "Base",
"ObjectId": [
[
"Value is 1"
],
""
]
},
"load": {
"ObjectId": 3,
"Class": "Base"
}
},
"Class": "Base"
},
{
"ObjectId": 2,
"Class": "Base",
"Stop": {}
}
]
}
這段代碼不假設輸入對象obj
的結構(它可以是字典或列表):
obj = {
"Id": 1,
"RESULT": [
{
"Check": {
"checkinstance": {
"ObjectId": 2,
"Class": "Base"
}
},
"Class": "Base"
},
{
"ObjectId": 2,
"Class": "Base",
"Start": {}
},
{
"Display": {
"part": {
"Class": "Base",
"ObjectId": [
[
"Value is 1"
],
""
]
},
"load": {
"ObjectId": 3,
"Class": "Base"
}
},
"Class": "Base"
},
{
"ObjectId": 2,
"Class": "Base",
"Stop": {}
}
]
}
def filter(obj):
if isinstance(obj, list):
for item in obj:
filter(item)
elif isinstance(obj, dict):
if "ObjectId" in obj:
print(obj["ObjectId"])
for v in obj.values():
if isinstance(v, (list, dict)):
filter(v)
filter(obj)
印刷:
2
2
[['Value is 1'], '']
3
2
如果您不想打印值而是將它們累積到列表中,則:
def filter2(obj):
if isinstance(obj, list):
for item in obj:
yield from filter2(item)
elif isinstance(obj, dict):
if "ObjectId" in obj:
yield obj["ObjectId"]
for v in obj.values():
if isinstance(v, (list, dict)):
yield from filter2(v)
print(list(filter2(obj)))
印刷:
[2, 2, [['Value is 1'], ''], 3, 2]
您可以使用遞歸函數搜索dict
所有鍵,然后搜索也是dict
的值的所有鍵:
# dictObj as in post
def findKey(key, d, result):
for k,v in d.items():
if k == key:
result.append(v)
if isinstance(v,dict):
findKey(key, v, result)
result = []
for key in dictObj:
if key == "RESULT":
if (type(jsonObj[key])== list):
for d in jsonObj[key]:
findKey('ObjectId', d, result)
print(result)
輸出:
[2, 2, [[ "Value is 1"], ""], 3, 2]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.