我正在尝试用 python 制作 3D 字典
我在按照我希望的方式关联列表中的值时遇到问题。
这是我的代码:
def nestedDictionary3D(L1, L2):
"""
Requires: L1 and L2 are lists
Modifies: Nothing
Effects: Creates a 3D dictionary, D, with keys of each item of list L1.
The value for each key in D is a dictionary, which
has keys of each item of list L2 and corresponding
values of empty dictionaries. Returns the new dictionary D.
"""
t1 = tuple(L1)
t2 = tuple(L2)
D = {t1: {t2: {}}}
return D
这是预期的输出和我的输出:
测试用例输入参数:
['dolphin', 'panda', 'koala'], ['habitat', 'diet', 'lifespan']
我的返回值:
{('dolphin', 'panda', 'koala'): {('habitat', 'diet', 'lifespan'): {}}}
预期返回值:
{'dolphin': {'diet': {}, 'habitat': {}, 'lifespan': {}}, 'panda': {'diet': {}, 'habitat': {}, 'lifespan': {}}, 'koala': {'diet': {}, 'habitat': {}, 'lifespan': {}}}
测试用例输入参数:
['Ann Arbor', 'San Francisco', 'Boston'], ['restaurants', 'parks', 'hotels']
我的返回值:
{('Ann Arbor', 'San Francisco', 'Boston'): {('restaurants', 'parks', 'hotels'): {}}}
预期返回值:
{'San Francisco': {'hotels': {}, 'parks': {}, 'restaurants': {}}, 'Ann Arbor': {'hotels': {}, 'parks': {}, 'restaurants': {}}, 'Boston': {'hotels': {}, 'parks': {}, 'restaurants': {}}}
有人可以解释我做错了什么吗?
谢谢!
请您参考如下方法:
为了实现这一点,您可以使用嵌套的 dict comprehension 表达式:
animal, property = ['dolphin', 'panda', 'koala'], ['habitat', 'diet', 'lifespan']
my_dict = {a: {p: {} for p in property} for a in animal}
my_dict 将保存值:
{'dolphin': {'diet': {}, 'habitat': {}, 'lifespan': {}},
'panda': {'diet': {}, 'habitat': {}, 'lifespan': {}},
'koala': {'diet': {}, 'habitat': {}, 'lifespan': {}}}
因此,您的函数可以简单地写成:
def nestedDictionary3D(L1, L2):
return {l1: {l2: {} for l2 in L2} for l1 in L1}
您不需要将 list 中的值类型转换为 tuple。
