[英]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?
So I want to make sure that a particular value of key is a primitive data type ie not a dictionary.所以我想确保键的特定值是原始数据类型,即不是字典。 If it is a dictionary, I want to recursively check till I reach the end.
如果它是一本字典,我想递归检查直到我到达最后。 ( base case-: no dictionary in the values) Let's say I have this code
(基本情况-:值中没有字典)假设我有这个代码
dict ={
"Roll No" : "1",
"Car" : {
"Ferrari" : "12",
"Pontiac" : "15"`
},
"Budget" : "3"
}
How do I get "Car" as the key which has the datatype of the values to be a dictionary?如何将“Car”作为具有字典的值的数据类型的键?
And how do I access the sub-dictionary ?以及如何访问子词典?
{ "Car":{
"Ferrari":"12",
"Pontiac":"15"
},
}
You can use python's type()
function to decide if the element is a dictionary, and thus when to recurse:您可以使用 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
There's a bunch of other ways to iterate over the dictionary, but I chose this method to illustrate the answer in a readable manner.还有很多其他方法可以迭代字典,但我选择这种方法是为了以可读的方式说明答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.