我正在尝试用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
以下是预期产出和我的产出:
测试用例输入参数:
^{pr2}$我的返回值:
{('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表达式:
其中
^{pr2}$my_dict
将保存值:因此,您的函数可以简单地写成:
不需要将
list
中的值类型转换为tuple
。在相关问题 更多 >
编程相关推荐