Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Acess deeply nested dicitionary 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT:
Wrong dictionary, edited it

>Solution :

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading