拆开嵌套字典的更干净方法 [英] Cleaner way to unpack nested dictionaries

查看:70
本文介绍了拆开嵌套字典的更干净方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从JSON格式的API批量接收数据.我希望仅将值存储在列表中.

I am receiving data in batches from an API in JSON format. I wish to store only the values, in a list.

原始数据看起来像这样,并且总是这样,即:所有{...}都看起来像第一个示例:

The raw data looks like this and will always look like this, i.e: all {...} will look like the first example:

data = content.get('data')
>>> [{'a':1, 'b':{'c':2, 'd':3}, 'e':4}, {...}, {...}, ...]

嵌套字典使这变得更加困难;我也需要打开包装.

The nested dictionary is making this harder; I need this unpacked as well.

这是我所拥有的,可以工作,但是感觉很糟糕:

Here is what I have, which works but it feels so bad:

unpacked = []
data = content.get('data')
for d in data:
    item = []
    for k, v in d.items():
        if k == 'b':
            for val in v.values():
                item.append(val)
        else:
            item.append(v)
    unpacked.append(item)

输出:

>>> [[1,2,3,4], [...], [...], ...]

我该如何改善呢?

推荐答案

您可以使用递归函数和一些类型测试:

You could use a recursive function and some type tests:

data = [{'a':1, 'b':{'c':2, 'd':3}, 'e':4}, {'f':5,'g':6}]

def extract_nested_values(it):
    if isinstance(it, list):
        for sub_it in it:
            yield from extract_nested_values(sub_it)
    elif isinstance(it, dict):
        for value in it.values():
            yield from extract_nested_values(value)
    else:
        yield it

print(list(extract_nested_values(data)))
# [1, 2, 3, 4, 5, 6]

请注意,它输出的是平面生成器,而不是列表列表.

Note that it outputs a flat generator, not a list of lists.

这篇关于拆开嵌套字典的更干净方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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