查找嵌套python字典和列表中所有出现的关键字 [英] Find all occurrences of a key in nested python dictionaries and lists

查看:632
本文介绍了查找嵌套python字典和列表中所有出现的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字典:

  {id:abcde,
key1 :blah,
key2:blah blah,
nestedlist:[
{id:qwerty,
nestednestedlist:[
{id:xyz,
keyA:blah blah blah},
{id:fghi,
keyZ​​:blah bla blah}],
anothernestednestedlist:[
{id:asdf,
keyQ:blah blah},
{id :yuiop,
keyW:blah}]}}}

基本上是一个具有任意深度的嵌套列表,字典和字符串的字典。



什么是遍历这个提取每个id键的值的最佳方法?我想实现相当于像// id这样的XPath查询。 id的值总是一个字符串。



所以从我的例子中,我需要的输出基本上是:

  [abcde,qwerty,xyz,fghi,asdf,yuiop] 
pre>

订单并不重要。

解决方案

 code> d = {id:abcde,
key1:blah,
key2:blah blah,
nestedlist
{id:qwerty,
nestednestedlist:[
{id:xyz,keyA:blah blah blah},
{id:fghi,keyZ​​:blah blah blah}],
anothernestednestedlist:[
{id:asdf,keyQ:blah blah },
{id:yuiop,keyW:blah}]}}}


def fun(d):
如果d中的'id':
d中的
d中的k
如果isinstance(d [k],列表)):
[k]:
为乐趣(i)中的j:
yield j






 > ;>>列表(fun(d))
['abcde','qwerty','xyz','fghi','asdf','yuiop']


I have a dictionary like this:

{ "id" : "abcde",
  "key1" : "blah",
  "key2" : "blah blah",
  "nestedlist" : [ 
    { "id" : "qwerty",
      "nestednestedlist" : [ 
        { "id" : "xyz",
          "keyA" : "blah blah blah" },
        { "id" : "fghi",
          "keyZ" : "blah blah blah" }],
      "anothernestednestedlist" : [ 
        { "id" : "asdf",
          "keyQ" : "blah blah" },
        { "id" : "yuiop",
          "keyW" : "blah" }] } ] } 

Basically a dictionary with nested lists, dictionaries and strings, of arbitrary depth.

What is the best way of traversing this to extract the values of every "id" key? I want to achieve the equivalent of an XPath query like "//id". The value of "id" is always a string.

So from my example, the output I need is basically:

["abcde", "qwerty", "xyz", "fghi", "asdf", "yuiop"]

Order is not important.

解决方案

d = { "id" : "abcde",
    "key1" : "blah",
    "key2" : "blah blah",
    "nestedlist" : [ 
    { "id" : "qwerty",
        "nestednestedlist" : [ 
        { "id" : "xyz", "keyA" : "blah blah blah" },
        { "id" : "fghi", "keyZ" : "blah blah blah" }],
        "anothernestednestedlist" : [ 
        { "id" : "asdf", "keyQ" : "blah blah" },
        { "id" : "yuiop", "keyW" : "blah" }] } ] } 


def fun(d):
    if 'id' in d:
        yield d['id']
    for k in d:
        if isinstance(d[k], list):
            for i in d[k]:
                for j in fun(i):
                    yield j


>>> list(fun(d))
['abcde', 'qwerty', 'xyz', 'fghi', 'asdf', 'yuiop']

这篇关于查找嵌套python字典和列表中所有出现的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆