[英]How do I tell if the value of a particular key in my dictionary is a dictionary so that I can solve programming questions based on this recursively?
所以我想確保鍵的特定值是原始數據類型,即不是字典。 如果它是一本字典,我想遞歸檢查直到我到達最后。 (基本情況-:值中沒有字典)假設我有這個代碼
dict ={
"Roll No" : "1",
"Car" : {
"Ferrari" : "12",
"Pontiac" : "15"`
},
"Budget" : "3"
}
如何將“Car”作為具有字典的值的數據類型的鍵?
以及如何訪問子詞典?
{ "Car":{
"Ferrari":"12",
"Pontiac":"15"
},
}
您可以使用 python 的type()
函數來決定元素是否是字典,從而決定何時遞歸:
searchDictionary( haystack, needle ):
for key in haystack.keys():
if type( haystack[key] ) is dict:
searchDictionary( haystack[key], needle )
elif type( haystack[key] ) is str:
# TODO - match string
if ( haystack[key] == needle ):
print( "Found at "+str(key) )
elif type( haystack[key] ) is int:
# TODO - match integer
pass
還有很多其他方法可以迭代字典,但我選擇這種方法是為了以可讀的方式說明答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.