apady111
apady111

Reputation: 3

How to update the values in a nested dictionary with a for loop?

I'm trying to update the values (1 and 2) in a nested dict using a for loop.

dict = {"first":{"firstInner":1}, "second":{"secondInner":2}}

for val, inner in dict:
    dict[val][inner] = 3

print(dict)

Desired output:

{"first":{"firstInner":3}, "second":{"secondInner":3}}

Actual output:

line 3, in <module>
    for val, inner in dict:
ValueError: too many values to unpack (expected 2)

Thank you.

Upvotes: 0

Views: 811

Answers (3)

Ram
Ram

Reputation: 4779

Avoid using dict as variable names as it is reserved.

Iterate over the outer dict items and then for every value of outer dict update the values.

dicts = {"first":{"firstInner":1}, "second":{"secondInner":2}}

for key, val in dicts.items():
    for i in val:
        val[i] = 3

print(dicts)
Output:
 
{'first': {'firstInner': 3}, 'second': {'secondInner': 3}}

Upvotes: 0

William Torkington
William Torkington

Reputation: 407

You might just need to iterate over all the keys within the inner dict, as so:

# For every key on the top level of the dict...
for outer in dict.keys():

    # ... get the keys of the inner dict...
    for inner in dict[outer].keys():

        # ... and set that value to three
        dict[outer][inner] = 3

check out .keys() documentation

Upvotes: 0

yudhiesh
yudhiesh

Reputation: 6799

You can do it like so, also do not use dict to name the dictionary, its already a reserved name.

In [9]: sample
Out[9]: {'first': 3, 'second': 3}

In [10]: sample = {"first":{"firstInner":1}, "second":{"secondInner":2}}

In [11]: for key,value in sample.items():
    ...:     for k in value.keys():
    ...:         value[k] = 3
    ...: 

In [12]: sample
Out[12]: {'first': {'firstInner': 3}, 'second': {'secondInner': 3}}

Upvotes: 1

Related Questions