[英]Search for item in list of dictionary
所以我有這個params
:
p = [{'quantity': 1}, {'args': {'id': 12345678, 'age': 12}}]
我希望能夠搜索quantity
並獲取值1
或args
鍵並獲取其doctionary
( {'id': 12345678, 'age: 12}
)
這是我嘗試過的:
def search(name: str, params: list[dict]):
try:
return next((x[name] for x in params if x), None)
except KeyError:
return None
如果我搜索quantity
的值:
search(name='quantity', params=p)
這個返回1
但如果我想要args
的價值:
search(name='args', params=p)
這個返回None
我有一組你可以使用的函數[ getNestedVal(p, 'args')
會返回{'id': 12345678, 'age: 12}
]...或者你可以使用這個生成器
def yieldNestedVals(obj, key):
if isinstance(obj, str): return
try: yield obj[key]
except: pass
if isinstance(obj, dict): obj = obj.values()
for i in (obj if hasattr(obj, '__iter__') else []):
for v in yieldNestedVals(i, key): yield v
里面search
喜歡
def search(name, params, defaultVal=None):
for v in yieldNestedVals(params, name): return v # return 1st generated value
return defaultVal # if nothing if generated
[ Ofc 你可以省略defaultVal
參數和最后一行,如果你想在沒有找到任何東西時返回None
,因為這是當 function 沒有遇到return
語句時的默認行為。 ]
現在search('args', p)
也應該返回{'id': 12345678, 'age: 12}
你也可以嘗試使用其他鍵:
# p = [{'quantity': 1}, {'args': {'id': 12345678, 'age': 12}}]
{k: search(k, p) for k in ['quantity', 'args', 'id', 'age', 'dneKey']}
會回來
{'quantity': 1, 'args': {'id': 12345678, 'age': 12}, 'id': 12345678, 'age': 12, 'dneKey': None}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.