繁体   English   中英

flatten function 适用于字典,但不适用于包含字典的列表

[英]flatten function works with dictionary but not a list containing dictionaries

我有我的 python 脚本,它在展平字典时可以完美运行,但是,当它是字典列表时,由于列表没有方法items() ,它将无法工作。

def flatten(dictionary, p_key=None, parent_key=False, separator='.'):
    items = []
    for key, value in dictionary.items():
        if parent_key:
            new_key = f"{str(p_key)}{separator}{key}"
        else:
            new_key = p_key if p_key else key
        if isinstance(value, mm):
            items.extend(flatten(
                dictionary=value,
                p_key=new_key,
                parent_key=True,
                separator=separator).items())
        elif isinstance(value, list):
            for k, v in enumerate(value):
                items.extend(flatten(
                    dictionary={str(k): v},
                    p_key=new_key,
                    parent_key=False,
                    separator=separator).items())
        else:
            items.append((new_key, value))
    return dict(items)


d = [{ 
    "_id" : 1, 
    "labelId" : [
        6422
    ], 
    "levels" : [
        {
            "active" : "true", 
            "level" : 3, 
            "actions" : [
                {
                    "isActive" : "true"
                }]
        }]
}]


x = flatten(d)

x = json_normalize(x)

print(x)

如果我删除周围的方括号,它将准确打印正确的扁平 dataframe。

有没有办法更新此代码,以便它基本上可以在该列表中 go ,然后开始展平字典?

您可以在 function 的开头添加代码以循环遍历列表。 以下代码适用于您提到的场景。

    items = []
    if isinstance(dictionary, list):
        for listval in dictionary:
            items.extend(flatten(listval).items())
    else:    
        for key, value in dictionary.items():

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM