使用嵌套数组在嵌套的OrderedDict中打印键和值的所有路径

时间:2019-05-19 00:55:53

标签: python dictionary path nested ordereddictionary

我正在尝试从具有数组和OderedDicts的嵌套数据结构中获取路径。问题是我在这里找到的函数Find a given key's value in a nested ordered dict python不能用于其中的数组。

我一直在Windows Environment上使用Python 3.7.3版进行尝试。

这就是我想要的,但是要使用数组:

location /some/path {
  content_by_lua '
    ngx.req.read_body()
    local args, err = ngx.req.get_post_args()

    if err == "truncated" or not args then return end

    local arg = args["some_arg"]
    if arg == nil then return end

    function escape(s)
      if s:match("[^A-Za-z0-9_/:=-]") then 
        return "\'"..s:gsub("\'", "\'\\\\\'\'").."\'" 
      else 
        return s 
      end
    end

    command = "/path/to/script.sh "..escape(arg)
    local handle = io.popen(command);
    local result = handle:read("*a");
    handle:close();
    ngx.print(result);
    ';
}

输出:

from collections import OrderedDict

mydict = OrderedDict ( {'a':
            OrderedDict ( {'b':
                OrderedDict ( [ ('chart_layout', '3'),
                 ('client_name', 'Sport Parents (Regrouped)'),
                 ('sort_order', 'asending'),
                 ('chart_type', 'pie'),
                 ('powerpoint_color', 'blue'),
                 ('crossbreak', 'Total')
                 ] ) } ) } )

def listRecursive (d, path = None):
    if not path: path = []
    for k, v in d.items ():
        if isinstance (v, OrderedDict):
            for path, found in listRecursive (v, path + [k] ):
                yield path, found
        if isinstance (v, str):
            yield path + [k], v

for path, found in listRecursive (mydict):
    print (path, found)

该集合不是实际的集合。它更嵌套在数组中。

['a', 'b', 'chart_layout'] 3
['a', 'b', 'client_name'] Sport Parents (Regrouped)
['a', 'b', 'sort_order'] asending
['a', 'b', 'chart_type'] pie
['a', 'b', 'powerpoint_color'] blue
['a', 'b', 'crossbreak'] Total

预期结果是: 标记路径 标签的结果

输入:


xml_order_dict = OrderedDict([('breakfast_menu',
                               OrderedDict([('food',
                                [OrderedDict([('name', 'Belgian Waffles'),
                                              ('price', '$5.95'),
                                              ('description',
                                               'Two of our famous Belgian Waffles '
                                               'with plenty of real maple syrup'),
                                              ('calories', '650')]),
                                 OrderedDict([('name',
                                           'Strawberry Belgian Waffles'),
                                              ('price', '$7.95'),
                                              ('description',
                                               'Light Belgian waffles covered with '
                                               'strawberries and whipped cream'),
                                              ('calories', '900')
                                             ])])]))])
def ListTags(d, key):
    for k, v in d.items ():
        if isinstance (v, OrderedDict):
            for found in listRecursive (v, key):
                yield found
        if k == key:
            yield v

for found in ListTags(xml_order_dict):
    print (found)

输出: 路径=结果

for found in ListTags(xml_order_dict):
    print (found)

输出的最后一个:

breakfast_menu['breakfast_menu']['food'][0]['name'] = Belgian Waffles
breakfast_menu['breakfast_menu']['food'][0]['price'] = $5.95
....

不好意思,我不是英语母语人士。

1 个答案:

答案 0 :(得分:1)

尝试此功能:

    {
  "name": "delivery",
  "description": "delivery system",
  "scripts": {
    "start": "run-p start:dev start:api",
    "start:dev": "webpack-dev-server --config webpack.config.dev.js --port 3000",
    "prestart:api": "node tools/createMockDb.js",
    "start:api": "node tools/apiServer.js"
  },
  "dependencies": {
    "list of dependiences"
  },
  "devDependencies": {
    "list of dev dependencies"
  },
  "engines": {
    "node": ">=8"
  },
  "babel": {
    "presets": [
      "babel-preset-react-app"
    ]
  },
    "env": {
      "browser": true,
      "node": true,
      "es6": true,
      "jest": true
    },
    "rules": {
      "no-debugger": "off",
      "no-console": "off",
      "no-unused-vars": "warn",
      "react/prop-types": "warn"
    },
    "settings": {
      "react": {
        "version": "detect"
      }
    },
    "root": true
  }
}

如果您这样做是为了生成可以重新创建列表的代码,请考虑考虑使用json formatting