Noah Eversole Noah Eversole - 10 months ago 77
Python Question

Creating a Nested 3D Dictionary in Python 2.7

I am trying to make a 3D dictionary in python

I am having issues associating the values in my lists the way that I want them.

Here is my code:

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

Here is the expected output and my output:

Test case input arguments:

['dolphin', 'panda', 'koala'], ['habitat', 'diet', 'lifespan']

My return value:

{('dolphin', 'panda', 'koala'): {('habitat', 'diet', 'lifespan'): {}}}

Expected return value:

{'dolphin': {'diet': {}, 'habitat': {}, 'lifespan': {}}, 'panda': {'diet': {}, 'habitat': {}, 'lifespan': {}}, 'koala': {'diet': {}, 'habitat': {}, 'lifespan': {}}}

Test case input arguments:

['Ann Arbor', 'San Francisco', 'Boston'], ['restaurants', 'parks', 'hotels']

My return value:

{('Ann Arbor', 'San Francisco', 'Boston'): {('restaurants', 'parks', 'hotels'): {}}}

Expected return value:

{'San Francisco': {'hotels': {}, 'parks': {}, 'restaurants': {}}, 'Ann Arbor': {'hotels': {}, 'parks': {}, 'restaurants': {}}, 'Boston': {'hotels': {}, 'parks': {}, 'restaurants': {}}}

Can someone explain what I am doing wrong?


Answer Source

In order to achieve this, you may use nested dict comprehension expression as:

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

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

where my_dict will hold the value:

{'dolphin': {'diet': {}, 'habitat': {}, 'lifespan': {}}, 
 'panda': {'diet': {}, 'habitat': {}, 'lifespan': {}}, 
 'koala': {'diet': {}, 'habitat': {}, 'lifespan': {}}}

Hence, your function could be simply written as:

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

You do not need to type-cast the values in the list to tuple.