簡體   English   中英

在 Python 中,如何從 dotted json 文件生成嵌套字典?

[英]In Python, how to generate nested dict from dotted json file?

我有一個json文件,例如:

{
    "a": 0.7615894039735099,
    "a.b": 0.7152317880794702,
    "a.c": 0.026490066225165563,
    "a.b.d": 0.0001,
    "f": 0.002,
    "f.g": 0.00003,
    "h.p.q": 0.0004
}

說整個字典被稱為“根”

我想以這種方式使用它

if "c" in root["a"] and if root["a"]["c"] > 0.0002:
   print("something")

有人能幫忙嗎? 太感謝了!

由於鍵是散列的 - 字符串鍵中是否存在點沒有語義意義,並​​且嘗試訪問root["a"]["c"]將導致如前所述的TypeError異常。 但是,您可以重新構建字典以具有您正在尋找的嵌套結構。 代碼大致如下所示:

root = {
    "a": 0.7615894039735099,
    "a.b": 0.7152317880794702,
    "a.c": 0.026490066225165563,
    "a.b.d": 0.0001,
    "f": 0.002,
    "f.g": 0.00003,
    "h.p.q": 0.0004
}

result = {}
for key, value in root.items():
     if not isinstance(key, str):
         result[key] = value
     is_nested = "." in key
     nesting_clash = any([k.startswith(key) for k in root if k != key])
     if nesting_clash:
         print(f"key {key} has nesting clash ; replacing with {key}._v")
         # continue # fixed after comment
         key = f"{key}._v"
         is_nested = True
     if not is_nested:
         result[key] = value
     key_parts = key.split(".")
     tmp = result
     for idx, key_part in enumerate(key_parts):
         default_value = {} if idx < len(key_parts) - 1 else value
         tmp[key_part] = tmp.get(key_part, default_value)
         tmp = tmp[key_part]

注意:您必須丟棄發生沖突的鍵(例如"a""ab" )或為它們創建默認行為。 在我的示例中,我決定丟棄它們。

編輯:我已經用 ._v 的密鑰替換替換了跳過。 這樣,您可以使用以下函數保留所有值並重建原始字典/JSON:

def unnest_dict(d, sep="."):
    result = {}
    for key, val in d.items():
        if not isinstance(val, dict):
            result[key] = val
            continue
        if "_v" in val:
            result[key] = val.pop("_v")
        unnested_val = unnest_dict(val, sep)
        for k, v in unnested_val.items():
            result[sep.join([key, k])] = v
    return result

看看下面的片段。


def merge(a, b, path=None):
    '''merges b into a'''
    if path is None: path = []
    for key in b:
        if key in a:
            if isinstance(a[key], dict) and isinstance(b[key], dict):
                merge(a[key], b[key], path + [str(key)])
            elif a[key] == b[key]:
                pass # same leaf value
            else:
                raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
        else:
            a[key] = b[key]
    return a


def convert_dotted_json(dottedJson):
    '''
    parameter
        dottedJson : dict type
    '''
    root = {}

    for key in dottedJson:
        split_key = key.split(".");
        split_key.reverse()
        value = dottedJson [key]
        curr = {split_key[0]: value};
        for ind in range(1, len(split_key)):
            curr = {split_key[ind]:curr}
        root = merge(root, curr)

    return root


test = {
    "a.b.c" : 0.026490066225165563,
    "a.b.d" : 0.0001,
    "f.g": 0.00003,
    "f.h": 0.00003,
    "h.p.q": 0.0004
}

# print(convert_dotted_json(test))

Andrew Cook 的回答中復制merge function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM