在python2.7中创建嵌套3D字典

2024-05-19 18:48:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用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': {}}}

有人能解释一下我做错了什么吗?在

谢谢!在


Tags: ofl1dictionaryeachsanannrestaurantsl2
1条回答
网友
1楼 · 发布于 2024-05-19 18:48:22

为了实现这一点,您可以使用嵌套dict comprehension表达式:

animal, property = ['dolphin', 'panda', 'koala'], ['habitat', 'diet', 'lifespan']

my_dict = {a: {p: {} for p in property}  for a in animal}

其中my_dict将保存值:

^{pr2}$

因此,您的函数可以简单地写成:

def nestedDictionary3D(L1, L2):
     return {l1: {l2: {} for l2 in L2}  for l1 in L1}

不需要将list中的值类型转换为tuple。在

相关问题 更多 >