簡體   English   中英

修改嵌套字典中的值

[英]Modify value in nested dictionary

這是我的代碼

def increase_by_one(d):
    for key, value in d.items():
        if d[value] == type(int): ## There is an error here
            d[value] = d[value] + 1
        else:
            d[key] += 1
    return d

我不確定是什么問題。 但我確信if d[value] == type(int)是錯誤的。 我該怎么改變它?

輸入

increase_by_one({'a':{'b':{'c':10}}})

產量

{'a':{'b':{'c':11}}}

輸入

increase_by_one({'1':2.7, '11':16, '111':{'a':5, 't':8}})

產量

{'1':3.7, '11':17, '111':{'a':6, 't':9}}

從您之前的帖子 ,我的答案已修復,以提供您想要的解決方案:

def increase_by_one(d):
    for key in d:
        try:
            d[key] += 1
        except TypeError:
            d[key] = increase_by_one(d[key])
    return d

每次嘗試將1添加到字典時,都會TypeError 既然你知道你正在處理嵌套字典,那么你再次調用你的函數。 這稱為遞歸。

>>> increase_by_one({'a':{'b':{'c':10}}})
{'a': {'b': {'c': 11}}}

>>> increase_by_one({'1':2.7, '11':16, '111':{'a':5, 't':8}})
{'1': 3.7, '11': 17, '111': {'a': 6, 't': 9}}

首先使用isinstance()iteritems()

for key, value in d.iteritems():

    if isinstance(value,int):
        ...

但是當你處理嵌套的dicts時,這是行不通的。 要么使用遞歸,要么你知道你的dict的深度,首先做一個像isinstance(value,dict)的檢查

您按值索引,但您應該使用該鍵,因為您已經在使用items() ,所以不需要從字典中獲取值:

def increase_by_one(d):
    for key, value in d.items():
        if type(value) == int:
            d[key] = value + 1
        else:
            increase_by_one(value) # if you want recursion
    return d

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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