简体   繁体   中英

Modify value in nested dictionary

This is my code

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

I am not sure what is wrong. But I am sure it's if d[value] == type(int) that is wrong. How can I change it ?

Input

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

Output

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

Input

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

Output

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

From your previous post , here's my answer fixed to provide the solution you want:

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

Every time you try to add 1 to a dictionary, a TypeError is raised. Since you know you're dealing with nested dictionaries, you call your function again. This is called recursion.

>>> 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}}

First of all use isinstance() and iteritems()

for key, value in d.iteritems():

    if isinstance(value,int):
        ...

But as you are dealing with nested dicts this won't do. Either use recursion or if you know the depth of your dict, first do a check like isinstance(value,dict)

You are indexing by value, but you should be using the key and no need to get the value from the dictionary since you are already using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM