我有一个嵌套字典,如下所示:
d = {"my momma" : {"your momma" : 1}, "flying on" : {"a broom" : 2}}
我需要将所有嵌套值(1和2)乘以2。
我该怎么做? 我只是无法访问它们。
答案 0 :(得分:0)
递归,如果你不知道你将有多少嵌套级别:
INDEX = []
def disMantle(target, depth):
# ensure a list for given depth
while len(INDEX) <= depth: INDEX.append([])
# analyze given target
for key in target:
atype = type(target[key])
if atype == dict:
# next depth
disMantle(target[key], depth+1)
elif atype in [int,float]:
# record the numeric values
INDEX[depth].append({'key':key,'value':target[key]})
d = {"my momma" : {"your momma" : 1}, "flying on" : {"a broom" : 2.0}}
disMantle(d, 0)
print INDEX[-1]
答案 1 :(得分:-2)
for key in d:
for skey in d[key]:
d[key][skey] *= 2
print d