How do I traverse and search a python dictionary?

前端 未结 7 1082
逝去的感伤
逝去的感伤 2020-12-04 18:52

I have nested dictionaries:

{\'key0\': {\'attrs\': {\'entity\': \'p\', \'hash\': \'34nj3h43b4n3\', \'id\': \'4130\'},
          u\'key1\': {\'attrs\': {\'ent         


        
7条回答
  •  伪装坚强ぢ
    2020-12-04 18:56

    If you want to solve the problem in a general way, no matter how many level of nesting you have in your dict, then create a recursive function which will traverse the tree:

    def traverse_tree(dictionary, id=None):
        for key, value in dictionary.items():
            if key == 'id':
                if value == id:
                    print dictionary
            else:
                 traverse_tree(value, id)
        return
    
    >>> traverse_tree({1: {'id': 2}, 2: {'id': 3}}, id=2)
    {'id': 2}
    

提交回复
热议问题