[英]Python - How to modify dictionary values - increment or decrement by an integer value
尝试从字典中的所有值中添加或减去一个整数值并返回修改后的字典时遇到问题。 下面是我的 Python 代码:
def increment(dictionary):
for entry in dictionary:
dictionary[entry] += 1 ## or -= 1
return dictionary
得到这个错误代码,但不知道如何克服它:TypeError: unsupported operand type(s) for +=: 'dict' and 'int'
有人可以告诉我我在俯瞰什么吗?
-编辑-
下面是一个字典的例子:{'x':{'y':{'z':15}}}
我想从 15 增加到 16。
递归递增的解决方案:
def increment(dictionary):
for entry in dictionary:
if type(dictionary[entry]) is dict:
dictionary[entry] = increment(dictionary[entry])
else:
dictionary[entry] += 1
return dictionary
d = {'x': {'y': {'z': 15}}}
print(increment(d))
打印{'x': {'y': {'z': 16}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.