Create dictionary from multi-dimensional list without duplicating keys
<p>I'd like to take a list of tuples with multiple elements and turn it into a multi-dimensional dictionary without repeating keys. So if the following is my original list:</p>

<pre><code>myList = [('jeep', 'red', 2002, 4), ('jeep', 'red', 2003, 6), ('jeep', 'blue', 2003, 4), ('bmw', 'black', 2015, 8)]
</code></pre>

<p>I would want to take the above and turn it into a dictionary in this format:</p>

<pre><code>{'jeep':
    {'red': [
        [2002, 4],
        [2003, 6]]
    'blue': [
        [2003, 4]]
    },
'bmw':
    {'black': [
        [2015, 8]]
    }
}
</code></pre>

<p>I seemed to be on the right path with Python's defaultdict, but I can't seem to completely solve this. Thanks!</p>

<p>Since what you want is essentially a tree data structure with a certain number of levels with lists for leaves, I'd be more explicit about it all by encapsulating the details inside a custom dictionary subclass because it could make the conversion extremely simple.</p>

<p>Here's a generic version of the data structure applied to your data:</p>

<pre><code>class TreeContainer(dict):
    def __init__(self, max_levels, leaf_factory=lambda: None, level=1):
        self.max_levels = max_levels
        self.level = level
        self.leaf_factory = leaf_factory

    def __missing__(self, key):
        if self.level &lt; self.max_levels:  # need another level?
            value = self[key] = type(self)(self.max_levels, self.leaf_factory, 
                                           self.level+1)
        else:
            value = self[key] = self.leaf_factory()
        return value

myList = [("jeep", "red", 2002, 4), ("jeep", "red", 2003, 6),
          ("jeep", "blue", 2003, 4), ("bmw", "black", 2015, 8)]

vehicles = TreeContainer(2, list)

for model, color, year, month in myList:  # convert list to dictionary
    vehicles[model][color].append([year, month])

from pprint import pprint
pprint(vehicles)
</code></pre>

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>{'bmw': {'black': [[2015, 8]]},
 'jeep': {'blue': [[2003, 4]], 'red': [[2002, 4], [2003, 6]]}}
</code></pre>

python dictionary defaultdict