Search code examples
pythondictionaryamalgamation

Python 2.7.12 - Replacing dictionary keys from a list nested in another dictionary


I have 2 dictionaries describing item categories and values of items in different places

categories = {'CAT1':['A','B','C'],'CAT2':['D','E','F']
items = {'A':[1.0],'B':[2.5, 1.0], 'C':[2.0], 'D':[0.2, 0.4], 'E':[0.1], 'F':[2.2, 2.4]}

I need a third dictionary that provides the values of the items grouped and sorted by category like:

new_dict = {'CAT1':[1.0, 2.5, 1.0, 2.0], 'CAT2':[0.2, 0.4, 0.1, 2.2, 2.4]}

I've trawled the existing questions but cant get anything to work. Way too rookie at this.


Solution

  • Use the following approach:

    result = {k: [item for i in sorted(items) if i in v for item in items[i]] 
                 for k,v in categories.items()}
    print(result)
    

    The output:

    {'CAT2': [0.2, 0.4, 0.1, 2.2, 2.4], 'CAT1': [1.0, 2.5, 1.0, 2.0]}