Search code examples
pythondictionarydefaultdict

Create dictionary from multi-dimensional list without duplicating keys


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:

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

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

{'jeep':
    {'red': [
        [2002, 4],
        [2003, 6]]
    'blue': [
        [2003, 4]]
    },
'bmw':
    {'black': [
        [2015, 8]]
    }
}

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


Solution

  • Using a lot of dict.setdefault...

    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])
    

    For each item in myList, 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...

    Gives you d:

    {'bmw': {'black': [[2015, 8]]},
     'jeep': {'blue': [[2003, 4]], 'red': [[2002, 4], [2003, 6]]}}