Xpath like query for nested python dictionaries

后端 未结 10 1652
情话喂你
情话喂你 2020-12-02 15:45

Is there a way to define a XPath type query for nested python dictionaries.

Something like this:

foo = {
  \'spam\':\'eggs\',
  \'morefoo\': {
               


        
10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 15:58

    def Dict(var, *arg, **kwarg):
      """ Return the value of an (imbricated) dictionnary, if all fields exist else return "" unless "default=new_value" specified as end argument
          Avoid TypeError: argument of type 'NoneType' is not iterable
          Ex: Dict(variable_dict, 'field1', 'field2', default = 0)
      """
      for key in arg:
        if isinstance(var, dict) and key and key in var:  var = var[key]
        else:  return kwarg['default'] if kwarg and 'default' in kwarg else ""   # Allow Dict(var, tvdbid).isdigit() for example
      return kwarg['default'] if var in (None, '', 'N/A', 'null') and kwarg and 'default' in kwarg else "" if var in (None, '', 'N/A', 'null') else var
    
    foo = {
      'spam':'eggs',
      'morefoo': {
                   'bar':'soap',
                   'morebar': {'bacon' : 'foobar'}
                  }
       }
    print Dict(foo, 'morefoo', 'morebar')
    print Dict(foo, 'morefoo', 'morebar', default=None)
    

    Have a SaveDict(value, var, *arg) function that can even append to lists in dict...

提交回复
热议问题