[英]How do I create and reference dictionaries that are the values within a dictionary dynamically?
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.我在倒数第二行收到TypeError: unhashable type: 'dict'并且我不知道如何动态构建(和引用)它。 (Realistically all of the values like 'folder1' would be taken from a list and referenced like outerlist[2], ie my_key = outerlist[2].) (实际上,像“folder1”这样的所有值都将从列表中获取并像 outerlist[2] 一样被引用,即 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?此外,如何为第一个键值对中的键“children”的值创建和引用['folder1', 'folder2'] 之类的列表?
After the line mydirectory[my_key] = my_value
, your dictionary looks like {'root': {}}
.在mydirectory[my_key] = my_value
行之后,您的字典看起来像{'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][my_value]...
将抛出TypeError: unhashable type: 'dict'
因为mydirectory[my_key]
是一个字典,而my_value
也是一个字典——字典和其他可变类型如列表不能是键字典——相反,你只需要修改mydirectory[my_key]
:
mydirectory[my_key][inner_key] = inner_value
Result:结果:
{'root': {'parent': 'none'}}
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.您正在尝试使用my_value
作为字典中的键,这是不允许的,因为可变类型不能是字典中的键。
So just remove my_value
as a key in that line.因此,只需删除my_value
作为该行中的键即可。
mydirectory[my_key][inner_key] = inner_value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.