亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在python中,如何最好地將key:value插入json,給定變量路徑和值

在python中,如何最好地將key:value插入json,給定變量路徑和值

絕地無雙 2021-12-17 16:07:36
我需要創建一個 json 文件,給出路徑及其值的字典。我編寫了一些用于添加條目的代碼,看起來它的功能和結果是正確的,但是作為 Python 新手,我想知道如何改進這一點,如果有一個功能相同的功能,模塊中已經存在包含在 python 2.7 中?   def path_to_list(path):        if isinstance(path, (str,)):            map_list = path.split("/")            for i, key in enumerate(map_list):                if key.isdigit():                    map_list[i] = int(key)        else:            map_list = path        return map_listdef add_to_dictionary(dic, keys, value):    for i, key in enumerate(keys[:-1]):        if i < len(keys)-1 and isinstance(keys[i+1], int):            # Case where current key should be a list, since next key is            # is list position            if key not in dic.keys():                # Case list not yet exist                dic[keys[i]] = []                dic[keys[i]].append({})                dic = dic.setdefault(key, {})            elif not isinstance(dic[key], list):                # Case key exist , but not a list                # TO DO : check how to handle                print "Failed to insert " + str(keys) + ", trying to insert multiple to not multiple  "                break            else:                # Case where the list exist                dic = dic.setdefault(key, {})        elif i < len(keys)-1 and isinstance(key, int):            # Case where current key is instance number in a list            try:                # If this succeeds instance already exist                dic = dic[key]            except (IndexError,KeyError):                # Case where list exist , but need to add new instances  ,                # as key instance  not exist                while len(dic)-1 < key:                    dic.append({})                dic = dic[key]        else:            # Case where key is not list or instance of list            dic = dic.setdefault(key, {})    # Update value    dic[keys[-1]] = value一些鍵可能已經存在,然后我只更新值。數字鍵在它可以有多個值之前表示該鍵,我正在數組中的這個地方添加/更新值
查看完整描述

1 回答

?
慕尼黑的夜晚無繁華

TA貢獻1864條經驗 獲得超6個贊

這是我使用嵌套字典實現的數據結構:


class Tree(dict):

    '''http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python'''


    def __missing__(d, k):

        v = d[k] = type(d)()

        return v


    def grow(d, path, v):

        ps = map(lambda k: int(k) if k.isdigit() else k, path.split('/'))

        reduce(lambda d, k: d[k], ps[:-1], d)[ps[-1]] = v

測試這個:


t = Tree()

t.grow('a/0/b/c', 1)

print t

t['a'][2]['b']['c'] = 'string'

print t

t.grow('a/2/b/c', 'new_string')

print t

給出:


{'a': {0: {'b': {'c': 1}}}}

{'a': {0: {'b': {'c': 1}}, 2: {'b': {'c': 'string'}}}}

{'a': {0: {'b': {'c': 1}}, 2: {'b': {'c': 'new_string'}}}}

但是您希望整數索引字典是數組。下面的例程遍歷嵌套的字典,將一些字典變成列表。它會進行一些復制,以免弄亂原始嵌套字典。我只會將它用作 outout 階段的一部分。


import numbers

def keys_all_int(d):

    return reduce(lambda r, k: r and isinstance(k, numbers.Integral), d.keys(), True)


def listify(d):

    '''

    Take a tree of nested dictionaries, and

    return a copy of the tree with sparse lists in place of the dictionaries

    that had only integers as keys.

    '''

    if isinstance(d, dict):

        d = d.copy()

        for k in d:

            d[k] = listify(d[k])

        if keys_all_int(d):

            ds = [{}]*(max(d.keys())+1)

            for k in d:

                ds[k] = d[k]

            return ds

    return d

測試這個:


t = Tree()

t.grow('a/0/b/c', 1)

print listify(t)

t['a'][2]['b']['c'] = 'string'

print listify(t)

t.grow('a/2/b/c', 'new_string')

print listify(t)

給出:


{'a': [{'b': {'c': 1}}]}

{'a': [{'b': {'c': 1}}, {}, {'b': {'c': 'string'}}]}

{'a': [{'b': {'c': 1}}, {}, {'b': {'c': 'new_string'}}]}

最后,如果您正在處理 JSON,請使用該json模塊:


import json

print json.dumps(listify(t),

    sort_keys=True, indent = 4, separators = (',', ': '))

給出:


{

    "a": [

        {

            "b": {

                "c": 1

            }

        },

        {},

        {

            "b": {

                "c": "new_string"

            }

        }

    ]

}


查看完整回答
反對 回復 2021-12-17
  • 1 回答
  • 0 關注
  • 354 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號