猿问

在python中,如何最好地将key:value插入json,给定变量路径和值

我需要创建一个 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_list



def 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


一些键可能已经存在,然后我只更新值。


数字键在它可以有多个值之前表示该键,我正在数组中的这个地方添加/更新值


绝地无双
浏览 362回答 1
1回答

慕尼黑的夜晚无繁华

这是我使用嵌套字典实现的数据结构:class Tree(dict):&nbsp; &nbsp; '''http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python'''&nbsp; &nbsp; def __missing__(d, k):&nbsp; &nbsp; &nbsp; &nbsp; v = d[k] = type(d)()&nbsp; &nbsp; &nbsp; &nbsp; return v&nbsp; &nbsp; def grow(d, path, v):&nbsp; &nbsp; &nbsp; &nbsp; ps = map(lambda k: int(k) if k.isdigit() else k, path.split('/'))&nbsp; &nbsp; &nbsp; &nbsp; reduce(lambda d, k: d[k], ps[:-1], d)[ps[-1]] = v测试这个:t = Tree()t.grow('a/0/b/c', 1)print tt['a'][2]['b']['c'] = 'string'print tt.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 numbersdef keys_all_int(d):&nbsp; &nbsp; return reduce(lambda r, k: r and isinstance(k, numbers.Integral), d.keys(), True)def listify(d):&nbsp; &nbsp; '''&nbsp; &nbsp; Take a tree of nested dictionaries, and&nbsp; &nbsp; return a copy of the tree with sparse lists in place of the dictionaries&nbsp; &nbsp; that had only integers as keys.&nbsp; &nbsp; '''&nbsp; &nbsp; if isinstance(d, dict):&nbsp; &nbsp; &nbsp; &nbsp; d = d.copy()&nbsp; &nbsp; &nbsp; &nbsp; for k in d:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d[k] = listify(d[k])&nbsp; &nbsp; &nbsp; &nbsp; if keys_all_int(d):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ds = [{}]*(max(d.keys())+1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for k in d:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ds[k] = d[k]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return ds&nbsp; &nbsp; 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 jsonprint json.dumps(listify(t),&nbsp; &nbsp; sort_keys=True, indent = 4, separators = (',', ': '))给出:{&nbsp; &nbsp; "a": [&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "b": {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "c": 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; {},&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "b": {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "c": "new_string"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ]}
随时随地看视频慕课网APP

相关分类

Python
我要回答