0

I'm trying to find a way to use a variable that contains the path as a way to set a value in a nested dictionary. I've looked into a lot of approaches, alot of them refer to the .get method, which is more for accessing the value then setting it.

This is what I basically want to try to do:

path: str = 'root,lv1,lv2,child' or path: list = [['root'],['lv1'],['lv2'],['child']]

and then assign

dictionary[path] = 'September' 

instead of the traditional way of

dictionary['root']['lv1']['lv2']['child'] = 'september'

If I try the string approach it simply adds it in as a new key at the end:

dictionary {'root': {'Lv1': {'Lv2': {'child': []}}}, ('root', 'Lv1', 'Lv2', 'child'): 'september'}

If I try the list approach this is the error I get:

Traceback (most recent call last):
  File "/Users/parmar/Library/Application Support/JetBrains/PyCharm2021.2/scratches/scratch_5.py", line 42, in <module>
    dictionary[path] = 'september'
TypeError: unhashable type: 'list'
sgitdev83
  • 15
  • 4
  • Just `dictionary[path]` will never work, unless `dictionary` is a very custom class. https://stackoverflow.com/a/14692747/476 is the canonical way to do this. – deceze Sep 10 '21 at 13:43

0 Answers0