使用 tuple 作为 json.dump 嵌套属性的键



不知道如何使用元组作为一组字符串。

我希望我的 json 看起来像:

'item': {
  'a': {
    'b': {
      'c': 'somevalue'
    }
  }
}

这可以通过以下方式完成:

item = {}
item['a']['b']['c'] = "somevalue"

但是abc是动态的,所以我知道我需要使用tuple,但这并不能满足我的意愿:

item = {}
path = ('a','b','c')
item[path] = "somevalue"
json.dump(item, sys.stdout)

所以我收到错误:

TypeError("key " + repr(key) + " is not a string"

如何动态获取item['a']['b']['c']

AFAIK 此任务没有内置函数,因此您需要编写几个递归函数:

def xset(dct, path, val):
    if len(path) == 1:
        dct[path[0]] = val
    else:
        if path[0] not in dct: dct[path[0]] = {}
        xset(dct[path[0]], path[1:], val)
def xget(dct, path):
    if len(path) == 1:
        return dct[path[0]]
    else:
        return xget(dct[path[0]], path[1:])

用法:

>>> d = {}
>>> xset(d, ('a', 'b', 'c'), 6)
>>> d
{'a': {'b': {'c': 6}}}
>>> xset(d, ('a', 'b', 'd', 'e'), 12)
>>> d
{'a': {'b': {'c': 6, 'd': {'e': 12}}}}
>>> xget(d, ('a', 'b', 'c'))
6

试试这个:

item = {}
for i in reversed(path):  
    tmp = {**item}
    item ={}
    item[i] = {**tmp} if path.index(i)!=len(path)-1 else 'somevalue'

最新更新