Home > Mobile >  How do I create and reference dictionaries that are the values within a dictionary dynamically?
How do I create and reference dictionaries that are the values within a dictionary dynamically?

Time:12-31

I would like to end up with something like this:

directory = {  'root' : {'parent': 'none',  'children': ['folder1','folder2']},
            'folder1': {'parent': 'root',  'children': ['folder3']},
            'folder2': {'parent': 'root',  'children': []},
            'folder3': {'parent': 'folder1', 'children': []} }

but without explicitly defining it in my code. If I try to build it from within the code like this:

mydirectory = {}

my_key = 'root'
my_value = {}
mydirectory[my_key] = my_value

inner_key = 'parent'
inner_value = 'none'
mydirectory[my_key][my_value][inner_key] = inner_value

print(mydirectory)

I get a TypeError: unhashable type: 'dict' on the next to last line and I am lost how to build (and reference) this dynamically. (Realistically all of the values like 'folder1' would be taken from a list and referenced like outerlist[2], i.e. my_key = outerlist[2].)

Additionally, how to both create and reference a list like ['folder1', 'folder2'] for the value of the key 'children' in the first key:value pair?

CodePudding user response:

Here in the line before the last line,

mydirectory[my_key][my_value][inner_key] = inner_value

You are trying to use my_value as the key in the dictionary which is not allowed as mutable types cannot be a key in dictionary.

So just remove my_value as a key in that line.

mydirectory[my_key][inner_key] = inner_value

CodePudding user response:

After the line mydirectory[my_key] = my_value, your dictionary looks like {'root': {}}.

The line mydirectory[my_key][my_value]... will throw TypeError: unhashable type: 'dict' because mydirectory[my_key] is a dictionary, and my_value is also a dictionary – dictionaries and other mutable types like lists cannot be keys for a dictionary – instead you only need to modify mydirectory[my_key]:

mydirectory[my_key][inner_key] = inner_value

Result:

{'root': {'parent': 'none'}}
  • Related