I have this nested dictionary:
JavaScript
x
5
1
{'palavra1': {'ID': {'AAA': {'w': 1, 'p': [3]}}, 'idf': None, 'd_f': 1},
2
'palavra2': {'ID': {'CCC': {'w': 2,'p': [1]}}, 'DDD': {'w': 3, 'p': [5]}},
3
'idf': None,
4
'd_f': 1}
5
I need to access the ‘w’ values and make them multiply by 3. What I’ve tried is:
JavaScript
1
5
1
for term, posting in nested_dict.items():
2
for doc_id, posting2 in posting.items():
3
for x, v in posting2.values():
4
nested_dict[term][doc_id][posting2][x] = (x * 3)
5
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:
JavaScript
1
8
1
def modify_w(d):
2
if 'w' in d:
3
d['w'] *= 3
4
for k,v in d.items():
5
if isinstance(v, dict):
6
modify_w(v)
7
modify_w(nested_dict)
8
Output:
JavaScript
1
6
1
>>> nested_dict
2
{'palavra1': {'ID': {'AAA': {'w': 3, 'p': [3]}}, 'idf': None, 'd_f': 1},
3
'palavra2': {'ID': {'CCC': {'w': 6, 'p': [1]}}, 'DDD': {'w': 9, 'p': [5]}},
4
'idf': None,
5
'd_f': 1}
6