简体   繁体   English

如何判断字典中特定键的值是否是字典,以便我可以基于此递归解决编程问题?

[英]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.

相关问题 如何将字典中的每个值都转换为浮点数? (递归) - How do I turn every value in my dictionary to a float? (recursively) 如何更改列表中字典中特定键的值类型? - How do I change the value type of a particular key in a dictionary in a list? 如何根据值从字典中筛选出密钥 - How can I filter a key out of a dictionary based on the value 如何在 for 循环中计算值作为字典键的一部分 - How do I counter value in a for loop as part of my dictionary key 我如何更新字典,以便如果键“ a”的值为“ c”,而不是键“ c”附加值“ a”? - How can I update a dictionary so that if key 'a' has a value of 'c' than the key of 'c' appends the value 'a'? 我如何将字典 append 作为现有字典键的另一个值 - How do I append a dictionary as another value to an existing dictionary key "在 Python 中,如何获取字典中特定键的下一个和上一个键:值?" - In Python, How can I get the next and previous key:value of a particular key in a dictionary? 如何遍历整数列表,并引用字典中最大的键(所有整数),使其小于当前值? - How can I iterate over a list of integers, and reference the largest key in my dictionary (all integers) so that it is smaller than current value? 如果密码在字典和键值对中,我如何解决此程序,以便使输入正常工作 - How do i fix this program so it makes the input work if the password is in the dictionary and key value pair 如何从字典值中删除[]和'',以便可以在csv文件中正确打印 - How do I remove [ ] and ' ' from my dictionary values so that I can print it properly in a csv file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM