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

61 views Asked by At

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.

2

There are 2 answers

1
RomanPerekhrest On BEST ANSWER

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]}
0
aghast On

As far as I can tell, your "sorting" of the result comes from the order of the original items in the categories dictionary.

Start by iterating over the keys and values of the categories dictionary:

result = {}
for cat, entries in categories.items(): # cat='CAT1', ent=['A', 'B', 'C']

The easy thing to do would be to use a defaultdict. But you can populate your resulting dictionary now with an empty list.

    result[cat] = []

Now, iterate over the list of entries:

    for entry in entries: # 'A', 'B', 'C'

Each entry in the entries list is a key into the items dictionary you provided, so look it up:

        ent_items = items[entry]  # ent_items = [1.0]

The result of that lookup (ent_items) is a list of float numbers. Concatenate it to the correct list in the result dictionary:

        result[cat] += ent_items   # result['CAT1'] = [1.0]

Notice that I haven't sorted anything, because your example doesn't appear to sort anything. The ordering of the dictionary keys (categories) doesn't matter, and everything else is determined by the sequence of items in the lists.