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>Using a lot of <code>dict.setdefault</code>...</p>

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

d = {}
for model, colour, year, month in myList:
    d.setdefault(model, {}).setdefault(colour, []).append([year, month])
</code></pre>

<p>For each item in <code>myList</code>, either get the current dictionary for the model or create the key with a new empty dict, then with that dict, either retrieve the list for that colour, or set the key with a new empty list, then append the year and month as a 2-element list to that list...</p>

<p>Gives you <code>d</code>:</p>

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

python dictionary defaultdict