嵌套的词典和列表/Glom库Python [英] Nested dicts and lists / glom lib python

查看:6
本文介绍了嵌套的词典和列表/Glom库Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问深度嵌套列表和词典。我正在试验Glom库,但在尝试检索国家/地区

时,我的第三个_KV密钥在下面的JSON对象上不起作用
from glom import glom

target = {
    "Result": {
        "Topics": [
            {
                "A": "abc",
                "D": 0,
                "Questions": [
                    {
                        "E": "jklm",
                        "P": "dsfs",
                        "Answers": [
                            {
                                "first": "string",
                                "second": "string",
                                "Country": "CH"
                            },
                            {
                                "first": "string",
                                "second": "string",
                                "Country": "NL"
                            }

                        ]
                    }
                ]
            }
        ]
    }
}

path = {
    "First_KV": ("Result.Topics", ["Questions"]),
    "Second_KV": ("Result.Topics", [("Questions", ["Answers"])]),
    "Third_KV": ("Result.Topics", [("Questions", "Answers", ["Country"])])
}
countries = glom(target, path["Third_KV"])

推荐答案

不太清楚您想要的最终json/数组/结构,但不依赖于任何库,您可以不使用简单的map()吗,例如

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
const jsonTest = {
  "Result": {
    "Topics": [{
      "A": "abc",
      "D": 0,
      "Questions": [{
        "E": "jklm",
        "P": "dsfs",
        "Answers": [{
            "first": "CHfirstCountry",
            "second": "CHsecondCountry",
            "Country": "CH"
          },
          {
            "first": "NLfirstCountry",
            "second": "NLsecondCountry",
            "Country": "NL"
          }
        ]
      }]
    }]
  }
};

const AnswersArray = jsonTest.Result.Topics[0].Questions[0].Answers;

let dictPerCountry = new Object();

AnswersArray.map((eachElement) => {
  dictPerCountry[eachElement.Country] = [eachElement.first, eachElement.second];
});

console.log({
  dictPerCountry
});

didicPerCountry将如下所示:

{
  "dictPerCountry": {
    "CH": [
      "CHfirstCountry",
      "CHsecondCountry"
    ],
    "NL": [
      "NLfirstCountry",
      "NLsecondCountry"
    ]
  }
}

这篇关于嵌套的词典和列表/Glom库Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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