python:查找具有值的所有键

时间:2018-01-16 07:39:08

标签: python python-3.x nested

我有一个如下字典:

svg2android

假设我想要查找所有值为&#39; <div class="widget-usb-backup dialog" ng-init="init()" ng-controller="UsbBackupController"> <div class="dialog-content-wrapper"> <div class="dialog-content"> <div class="heading inner-content usb-backup-title">{{ "COMMON_LOC_COPY_TO_USB" | translate}}</div> <div class="dialog-msg inner-content usb-backup-instruction">{{ "LOC_USB_BACKUP_MESSAGE" | translate}}</div> <div class="code-content inner-content "> <div class="dropdown-list" ng-controller="collapsible-controller" layout-align="center"> <select ng-model="selectedDevice" ng-options="device for device in allExternalStorageDevices" ng-change="selectExternalStorageDevice();collapse();" ng-controller="UsbBackupController"> </select> </div> <div class="button-container inner-content"> <button class="button button-green button-long" value="" ng-click="submit()" es-enter="submit()"> {{ "COMMON_LOC_COPY_TO_USB" | translate}}</button> </div> </form> </div> <div class="dialog-additional-links"> <a href="javascript:void(0)" class="cancel-link" ng-click="closeModal()">{{ "COMMON_LOC_CANCEL" | translate}}</a> </div> </div> </div> 的所有键&#39;如果是嵌套,则键应该用点分隔。

因此输出应该是列表mydict = {'a' : 'apple', 'b' : 'bobb', 'c' : { 'd' : 'dog' }, 'e' : 'dog' }

现在,如果我在python 3中编写下面的代码,它只输出&#39; dog&#39;。

['e', 'c.d']

如何获取嵌套密钥?

4 个答案:

答案 0 :(得分:9)

您可以使用如下的递归函数:

$latest_activites = User::with('activites')
                         ->where("activites",function($query){

             $query->where("created_at",">=",Carbon::now()->subDays(3));

        })->latest()->get();

测试:

def find_key(mydict, pre=tuple()):
    for key, value in mydict.items():
        if isinstance(value, dict):
            yield from find_key(value, pre=pre+(key,))
        elif value == 'dog':
            if pre:
                yield '.'.join(pre + (key,))
            else:
                yield key

答案 1 :(得分:2)

你可以使用递归(虽然@Kasramvd打败了它,这里是一个非生成器版本的好措施):

>>> def find_key(value, d, level=None, acc=None):
...     acc = acc if acc is not None else []
...     level = level if level is not None else []
...     for k,v in d.items():
...         if isinstance(v, dict):
...             find_key(value, v, level=[*level, k], acc=acc)
...         elif v == value:
...             acc.append('.'.join([*level,k]))
...     return acc
...
>>>
>>> find_key('dog', mydict)
['c.d', 'e']

使用Kasramvd的混乱测试用例:

>>> mydict = {'a' : 'apple',
...      'b' : 'bobb',
...     'c' : {
...          'd' : 'dog'
...        },
...       'e' : 'dog',
...      'k':{'f':{'c':{'x':'dog'}}}}
>>> find_key('dog', mydict)
['c.d', 'e', 'k.f.c.x']

答案 2 :(得分:1)

您还可以使用列表推导的递归:

mydict1 = {'a' : 'apple',
    'b' : 'bobb',
    'c' : {
       'd' : 'dog'
      },
     'e' : 'dog'
     }

mydict = {'a' : 'apple',
 'b' : 'bobb',
'c' : {
     'd' : 'dog'
   },
  'e' : 'dog',
 'k':{'f':{'c':{'x':'dog'}}}}

s = [mydict1, mydict]
def get_val(d, target='dog'):
  return reduce(lambda x, y:([x] if isinstance(x, str) else x)+([y] if isinstance(y, str) else y), list(filter(None, [a if b == target else "{}.{}".format(a, get_val(b)) if isinstance(b, dict) else None for a, b in d.items()])))


new_s = list(map(get_val, s))

输出:

[['c.d', 'e'], ['c.d', 'e', 'k.f.c.x']]

答案 3 :(得分:0)

你走了:

mydict = {'a' : 'apple',
     'b' : 'bobb',
    'c' : {
         'd' : 'dog'
       },
      'e' : 'dog',
     'k':{'f':{'c':{'x':'dog'}}},

      'p':{'r':{'h':{'m':{'n':{'o':{'a':{'b':{'t':{'z':{'a':{'b':{'c':{'d':{'e':{'f':{'g':'dog'}}}}}}}}}}}}}}}}







          }

your_word='dog'

result = []

for key,value in mydict.items():
    if value==your_word:
        result.append(key)
    elif isinstance(value,dict):

        def recursive_approach(my_dict, nested_dict=key):

            for i, j in my_dict.items():
                if isinstance(j, dict):

                    nested_dict = "{}.{}".format(nested_dict, i)


                    return recursive_approach(j, nested_dict)
                else:
                    if nested_dict == '':

                        if j == your_word:
                            result.append(i)
                    else:
                        if j == your_word:
                            result.append("{}.{}".format(nested_dict, i))


        recursive_approach(value)





print(result)

输出:

['p.r.h.m.n.o.a.b.t.z.a.b.c.d.e.f.g', 'k.f.c.x', 'e', 'c.d']