【问题标题】:Creating list of lists from dictionary with irregular levels of nesting从字典中创建具有不规则嵌套级别的列表列表
【发布时间】:2021-06-07 13:25:18
【问题描述】:

我有一个来自 Python 3.8 中 cURL 调用的字典,我想创建一个列表,其中包含来自两个键的信息,然后写入 csv 文件。

字典实际上只有一个键值对,其值是包含我需要的信息的字典列表。在嵌套字典中,我对键值对 'conceptId' 和 'fsn' 感兴趣(这是另一个具有两个键值对的嵌套字典,我只需要其中的 'term')。

这是一个包含两个“项目”的字典的 sn-p,尽管实际文件要大得多。

res_json = {'items': [{'conceptId': '15964901000119107', 'active': True, 'definitionStatus': 'PRIMITIVE', 'moduleId': '900000000000207008', 'fsn': {'term': 'Atypical atrial flutter (disorder)', 'lang': 'en'}, 'pt': {'term': 'Atypical atrial flutter', 'lang': 'en'}, 'id': '15964901000119107'}, {'conceptId': '10811961000119109', 'active': True, 'definitionStatus': 'FULLY_DEFINED', 'moduleId': '900000000000207008', 'fsn': {'term': 'Cardiac arrest due to incomplete miscarriage (disorder)', 'lang': 'en'}, 'pt': {'term': 'Cardiac arrest due to incomplete miscarriage', 'lang': 'en'}, 'id': '10811961000119109'}]}

期望的输出:

output = ['15964901000119107', 'Atypical atrial flutter (disorder)'], ['10811961000119109', 'Cardiac arrest due to incomplete miscarriage (disorder)']

这是我目前的代码 (flatten_json)


#Flatten json 
def flatten_json(y):
    out = {}

    def flatten(x, name=''):
        if type(x) is dict:
            for a in x:
                flatten(x[a], name + a + '_')
        elif type(x) is list:
            i = 0
            for a in x:
                flatten(a, name + str(i) + '_')
                i += 1
        else:
            out[name[:-1]] = x

    flatten(y)
    return out



flat = flatten_json(res_json)
json_normalize(flat)
output_list = []

for k, v in flat.items():
    if "conceptId" in k:
        output_list.append(v)
    if "fsn_term" in k:
        output_list.append(v)
        
for k, v in flat.items():
    if "fsn" in l:
        output[k] = v

这将返回一个包含交替顺序值的列表,但不是我可以写入 csv 的列表列表。

>>>output_list: ['15964901000119107', 'Atypical atrial flutter (disorder)', '10811961000119109', 'Cardiac arrest due to incomplete miscarriage (disorder)']

如何改进我的代码?

【问题讨论】:

  • 鉴于此站点有助于解决特定的技术问题,而不是对代码或建议的开放式请求。在我看来,这个问题更适合在Code Review Forum 中提出。 Code Review 是一个针对同行程序员代码审查的问答网站。在发布您的问题之前,请阅读有关如何在本网站上正确提问的相关指南。
  • 我的问题确实是具体的和技术性的。我正在寻求一种从a点到b点的方法,以显示我到目前为止的尝试以及我被困在哪里......根据我的经验,这似乎是在这里提问的标准方式。谢谢你的链接,如果我冒犯了你,我很抱歉。

标签: json python-3.x dictionary nested


【解决方案1】:

事实证明,我需要创建一个仅包含“items”值的更简单的字典,即字典列表,然后简单地调用我需要的键值对并将它们添加到列表中。

items = {}

    for k, v in res_json.items():
        if k == 'items':
            items[k] = v
        
output = sorted([[x['conceptId'], x['fsn']['term']] for x in items['items']])

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2021-04-19
    • 2018-01-16
    相关资源
    最近更新 更多