【问题标题】:Merging nested dictionary's to Json file for d3 sunburst将嵌套字典合并到 d3 sunburst 的 Json 文件
【发布时间】:2018-06-25 02:31:22
【问题描述】:

我遇到的问题是我需要一个小而重度嵌套的字典列表来合并成一个字典。所有的小字典都有完全相同的布局

{
"name": "root",
"tax": "Tax level: domain",
"children": [
    {
        "name": "Bacteria",
        "tax": "Tax level: Kingdom",
        "children": [
            {
                "name": "Firmicutes",
                "tax": "Tax level: Phylum",
                "children": [
                    {
                        "name": "Bacillidae",
                        "tax": "Tax level: Class",
                        "children": [
                            {
                                "name": "Bacillinae",
                                "tax": "Tax level: Order",
                                "children": [
                                    {
                                        "name": "Bacillini",
                                        "tax": "Tax level: Family",
                                        "children": [
                                            {
                                                "name": "Bacillus",
                                                "tax": "Tax level: Genus",
                                                "children": [
                                                    {
                                                        "name": "",
                                                        "size": 5,
                                                        "tax": "Tax level: Species"
                                                    }
                                                ]
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }
]}

尝试的不同解决方案只合并了第一个字典; "name": "root" 得到了这个结果:

{
"name": "root",
"tax": "Tax level: domain",
"children": [
    {
        "name": "Bacteria",
        "tax": "Tax level: Kingdom",
        "children": [
            {
                "name": "Firmicutes",
                "tax": "Tax level: Phylum",
                "children": [
                    {
                        "name": "Bacillidae",
                        "tax": "Tax level: Class",
                        "children": [
                            {
                                "name": "Bacillinae",
                                "tax": "Tax level: Order",
                                "children": [
                                    {
                                        "name": "Bacillini",
                                        "tax": "Tax level: Family",
                                        "children": [
                                            {
                                                "name": "Bacillus",
                                                "tax": "Tax level: Genus",
                                                "children": [
                                                    {
                                                        "name": "",
                                                        "size": 5,
                                                        "tax": "Tax level: Species"
                                                    }
                                                ]
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        "name": "Bacteria",
        "tax": "Tax level: Kingdom",
        "children": [
            {
                "name": "Thermotogae",
                "tax": "Tax level: Phylum",
                "children": [
                    {
                        "name": "Thermotogae",
                        "tax": "Tax level: Class",
                        "children": [
                            {
                                "name": "Thermotogales",
                                "tax": "Tax level: Order",
                                "children": [
                                    {
                                        "name": "Thermotogaceae",
                                        "tax": "Tax level: Family",
                                        "children": [
                                            {
                                                "name": "Thermotoga",
                                                "tax": "Tax level: Genus",
                                                "children": [
                                                    {
                                                        "name": "",
                                                        "size": 5,
                                                        "tax": "Tax level: Species"
                                                    }
                                                ]
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }

但我需要的是删除重复项和附加其他行。如下所示(手动完成):

{
"name": "root",
"tax": "Tax level: domain",
"children": [
    {
        "name": "Bacteria",
        "tax": "Tax level: Kingdom",
        "children": [
            {
                "name": "Firmicutes",
                "tax": "Tax level: Phylum",
                "children": [
                    {
                        "name": "Bacillidae",
                        "tax": "Tax level: Class",
                        "children": [
                            {
                                "name": "Bacillinae",
                                "tax": "Tax level: Order",
                                "children": [
                                    {
                                        "name": "Bacillini",
                                        "tax": "Tax level: Family",
                                        "children": [
                                            {
                                                "name": "Bacillus",
                                                "tax": "Tax level: Genus",
                                                "children": [
                                                    {
                                                        "name": "",
                                                        "size": 5,
                                                        "tax": "Tax level: Species"
                                                    }
                                                ]
                                            }
                                        ]
                                    }
                                ]
                            },
                            {
                                "name": "Firmicutes",
                                "tax": "Tax level: Class",
                                "children": [
                                    {
                                        "name": "Tissierellia",
                                        "tax": "Tax level: Order",
                                        "children": [
                                            {
                                                "name": "unclassified Tissierellia",
                                                "tax": "Tax level: Family",
                                                "children": [
                                                    {
                                                        "name": "Tepidimicrobium",
                                                        "tax": "Tax level: Genus",
                                                        "children": [
                                                            {
                                                                "name": "",
                                                                "size": 5,
                                                                "tax": "Tax level: Species"
                                                            }
                                                        ]
                                                    }
                                                ]
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]
            },
            {
                "name": "Thermotogae",
                "tax": "Tax level: Phylum",
                "children": [
                    {
                        "name": "Thermotogae",
                        "tax": "Tax level: Class",
                        "children": [
                            {
                                "name": "Thermotogales",
                                "tax": "Tax level: Order",
                                "children": [
                                    {
                                        "name": "Thermotogaceae",
                                        "tax": "Tax level: Family",
                                        "children": [
                                            {
                                                "name": "Thermotoga",
                                                "tax": "Tax level: Genus",
                                                "children": [
                                                    {
                                                        "name": "",
                                                        "size": 5,
                                                        "tax": "Tax level: Species"
                                                    }
                                                ]
                                            }
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }
]}

我编写的代码接受一个字典列表,并将它们一一发送到合并字典的合并模块。

tempCount = -1                                                                      #initializes Counter for dictionary, starts at -1 to compensate index errors.
try:
    for i in tempDicts:                                                             #Loops over list with small dictionarys
        tempCount += 1                                                              #Adds to the counter
        if tempCount <=0:                                                           #if the counter is 0, it adds the first and second dictionary to a merged dictionary
            result = merge(tempDicts[tempCount], tempDicts[tempCount+1])
        elif tempCount > 0:                                                         #if the counter is higher than 0, it merges the small dictionary to the already merged dictionary.
            result = merge(result, tempDicts[tempCount+1])
        else:
            print("Error in merging temporary dictionarys!")                        #catches random errors.
    print("test")
    print(result)
    print(reduce(result))

except IndexError:                                                                  #catches index out of range errors.
    print("Finished Merging")                                                       #if there are no more small dicts to merge, it gets an error and stops.

【问题讨论】:

  • 您可能想减小嵌套字典示例的大小,我们明白了
  • @cᴏʟᴅsᴘᴇᴇᴅ 我想看看你解决这个问题的风格
  • 查字典太难了。你能不能把它缩小到一个更小的?
  • @RoadRunner 恐怕我不能,字典需要在这个标识上是静态的。

标签: json python-3.x merge nested


【解决方案1】:

有了RFC 7386,我们就有了 JSON 合并。 并且只需使用数组的特殊过程扩展 JSON 合并。

def merge_patch(target, patch, arraykey="name"):
    if isinstance(patch, dict):
        if not isinstance(target, dict):
            target = {}
        for name, value in patch.items():
            if value is None and name in target:
                del target[name]
            else:
                if name in target:
                    target[name] = merge_patch(target[name], value, arraykey)
                else:
                    target[name] = value
        return target
    elif isinstance(patch, list):
        if not isinstance(target, list):
            target = []
        dicted_target = {item[arraykey]:item for item in target}
        dicted_patch = {item[arraykey]:item for item in patch}
        for name, value in dicted_patch.items():
            if value is None and name in dicted_target:
                del dicted_target[name]
            else:
                if name in target:
                    dicted_target[name] = merge_patch(dicted_target[name], value, arraykey)
                else:
                    dicted_target[name] = value
        return list(dicted_target.values())
    else:
        return patch

print(merge_patch('x', 'y'))
print(merge_patch({'a':1},{'b':2}))
print(merge_patch([{'name':'a','x':'z'},{'name':'b'}],[{'name':'a','x':'y'},{'name':'c'}]))

我们有。请注意,目标将被函数改变(需要一些工作才能使其成为纯函数)。

【讨论】:

  • 在pairs() 函数上导入存储库后出错。 File "XMLtoJSON.py", line 146, in merge_patch for name, value in patch.pairs(): AttributeError: 'dict' object has no attribute 'pairs'
  • 修复了一些错误
猜你喜欢
  • 2016-08-19
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 2023-02-23
  • 2021-09-25
  • 2011-05-13
  • 1970-01-01
  • 2023-03-19
相关资源
最近更新 更多