python向dict里添加_如何在python dict中向特定的’path’添加一些数据?

本文介绍了一个Python函数`add_value`,用于在字典中根据路径动态创建嵌套结构并添加值。通过递归实现,避免了为不同长度路径编写大量代码。示例展示了如何使用该函数在字典中添加多级嵌套的键值对。
摘要由CSDN通过智能技术生成

例如,我想定义一个函数:

def add_value(dic, path, value):

# dict is a Dictionary to be modified

# path is a list, like ['A', 'B', 'C', ...]

# value is a list or tuple

...

...

return dic

d = {}

d = add_value(d, ['A', 'B'], ('log.txt', '12KB'))

print(d)

d = add_value(d, ['X', 'Y', 'Z'], ('backup.bin', '17MB'))

print(d)

d = add_value(d, ['X', 'Y', 'Z'], ('file.lst', '5KB'))

print(d)

输出应该是下一个:

{'A': {'B': {'log.txt': '12KB'}}}

{'A': {'B': {'log.txt': '12KB'}}, 'X': {'Y': {'Z': {'backup.bin': '17MB'}}}}

{'A': {'B': {'log.txt':'12KB'}}, 'X': {'Y': {'Z': {'backup.bin': '17MB', 'file.lst': '5KB'}}}}

我试过这样的:

import json

def add_value(dic, path, value):

# dic is a dict to be modified

# path is a list

# value is a tumple like ('file1.txt': '20kb')

length = len(path)

if length == 1:

if path[0] not in dic:

dic[path[0]] = {}

else:

dic[path[0]].append(value)

return dic

elif length == 2:

if path[0] not in dic:

dic[path[0]] = {}

if path[1] not in dic[path[0]]:

dic[path[0]][path[1]] = {}

dic[path[0]][path[1]][value[0]] = value[1]

return dic

elif length == 3:

if path[0] not in dic:

dic[path[0]] = {}

if path[1] not in dic[path[0]]:

dic[path[0]][path[1]] = {}

if path[2] not in dic[path[0]][path[1]]:

dic[path[0]][path[1]][path[2]] = {}

dic[path[0]][path[1]][path[2]][value[0]] = value[1]

return dic

elif length == 4:

if path[0] not in dic:

dic[path[0]] = {}

if path[1] not in dic[path[0]]:

dic[path[0]][path[1]] = {}

if path[2] not in dic[path[0]][path[1]]:

dic[path[0]][path[1]][path[2]] = {}

if path[3] not in dic[path[0]][path[1]][path[2]]:

dic[path[0]][path[1]][path[2]][path[3]] = {}

dic[path[0]][path[1]][path[2]][path[3]][value[0]] = value[1]

return dic

else:

return

d = {}

d = add_value(d, ['A', 'B'], ('log.txt', '12KB'))

d = add_value(d, ['A', 'B', 'C',], ('log2.txt', '34kb'))

d = add_value(d, ['A', 'G'], ('log2.txt', '2kb'))

d = add_value(d, ['X', 'Y', 'Z'], ('log2.txt', '3kb'))

print(json.dumps(d, indent=2))

输出是:

{ "X": {

"Y": {

"Z": {

"log2.txt": "3kb"

}

} }, "A": {

"G": {

"log2.txt": "2kb"

},

"B": {

"C": {

"log2.txt": "34kb"

},

"log.txt": "12KB"

} } }

这看起来很愚蠢.

如果我想add_value(d,[‘A’,’B’,’C’,…,’Y’,’Z’],(‘1.jpg’,’1.2MB’)),我需要写大量的代码.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值