Home > other >  how do i update dictionary in second for loop if type is not dict
how do i update dictionary in second for loop if type is not dict

Time:12-12

dic={"a":1,
   "b":5,
   "c":{"a":3,"c":-5,"d":{"a":1,"b":3}}}

and output is

{"a":5,"b":8,"c":-5,"d":0}

i am facing updating dictionary in second for loop

d=dict()
d2=dict()
for i in dic:
    c_dict=dic[i]
    if type(dic[i])!=dict:              #a:1 ,b:5
        d[i] = dic[i]
    else:
        for j in c_dict:
            value=c_dict[j]
            if type(value)!=dict:
                d2[j]=value

d2[j]=value for this i have to update with previous values of a and b

CodePudding user response:

The question here is whether the d key should be in the resulting dictionary. If it's to be ignored then:

dic = {"a": 1,
       "b": 5,
       "c": {"a": 3, "c": -5, "d": {"a": 1, "b": 3}}}

result = {}

def process(d):
    for k, v in d.items():
        if isinstance(v, dict):
            process(v)
        else:
            result[k] = result.get(k, 0)   v

process(dic)

print(result)

Output:

{'a': 5, 'b': 8, 'c': -5}

Note:

Assumption here is that all values are either dictionary or numeric types

CodePudding user response:

  1. As you need to implement the same for multiple levels of a dict, you need a recursive method, handle a dict:

    • if the value is int, add it
    • if the value is dict, call the method on that value
  2. As you want to do an addition with every value, you'd need to ensure there is a value before adding, you can solve that with a defaultdict(int) which will make sure there is always a zero for every key you ask, so you can directly do =

from collections import defaultdict


def add_to_dict(base, more_values):
    for k, val in more_values.items():
        base[k]  = 0  # for keys like 'd'
        if isinstance(val, dict):
            add_to_dict(base, val)
        else:
            base[k]  = val


data = {"a": 1, "b": 5,
        "c": {"a": 3, "c": -5, "d": {"a": 1, "b": 3}}}

result = defaultdict(int)
add_to_dict(result, data)

print(result)  # {"a": 5, "b": 8, "c": -5, "d": 0}
  • Related