簡體   English   中英

Python - 如何修改字典值 - 按整數值遞增或遞減

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM