【问题标题】:flatten function works with dictionary but not a list containing dictionariesflatten 函数适用于字典,但不适用于包含字典的列表
【发布时间】:2021-06-20 04:48:51
【问题描述】:

我的 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)

如果我删除周围的方括号,它将准确地打印正确的展平数据框。

有没有办法更新此代码,使其基本上可以进入该列表,然后开始展平字典?

【问题讨论】:

    标签: python pandas dictionary flatten


    【解决方案1】:

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

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

    【讨论】:

    • 仅当列表中有一本字典时才有效?例如,如果列表中有两个字典怎么办
    • 它似乎只是检索字典中的最后一条记录而不是打印所有内容,我认为这是因为当有重复键时你不能将字典附加到另一个字典,它必须是唯一的跨度>
    猜你喜欢
    • 2014-07-24
    • 2021-06-25
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    相关资源
    最近更新 更多