Skip to content
Advertisement

Access a deeply nested dictionary and multiply values

I have this nested dictionary:

{'palavra1': {'ID': {'AAA': {'w': 1, 'p': [3]}}, 'idf': None, 'd_f': 1}, 
 'palavra2': {'ID': {'CCC': {'w': 2,'p': [1]}}, 'DDD': {'w': 3, 'p': [5]}}, 
 'idf': None, 
 'd_f': 1}

I need to access the ‘w’ values and make them multiply by 3. What I’ve tried is:

for term, posting in nested_dict.items():
    for doc_id, posting2 in posting.items():
        for x, v in posting2.values():
            nested_dict[term][doc_id][posting2][x] = (x * 3)

It doesn’t work, and I’ve tried other ways and it doesn’t work as well. Any tips?

EDIT: Wrong dictionary, edited it

Advertisement

Answer

You could use a recursive function that modifies “w” values:

def modify_w(d):
    if 'w' in d:
        d['w'] *= 3
    for k,v in d.items():
        if isinstance(v, dict):
            modify_w(v)
modify_w(nested_dict)

Output:

>>> nested_dict
{'palavra1': {'ID': {'AAA': {'w': 3, 'p': [3]}}, 'idf': None, 'd_f': 1},
 'palavra2': {'ID': {'CCC': {'w': 6, 'p': [1]}}, 'DDD': {'w': 9, 'p': [5]}},
 'idf': None,
 'd_f': 1}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement