Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to rearrange dictionary keys and values efficiently (according to this example)?

I have a dictionary that is structured like so:

Current input:

current_dict = {'TP': {'class_A': 100,
                       'class_B': 200,
                       'class_C': 300},
                'FP' : {'class_A': 50,
                       'class_B': 60,
                       'class_C': 70},
                'FN' : {'class_A': 10,
                       'class_B': 20,
                       'class_C': 30}
                }

However, I would like every class to be the top-level key name and the values to contain the TP, FP, FN counts per class, like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Desired output:

desired_dict = {'class_A': {'TP' : 100, 'FP': 50, 'FN': 10},
                'class_B': {'FP' : 200, 'FP': 60, 'FN': 70},
                'class_C': {'FN' : 300, 'FP': 70, 'FN': 30},
                }

My current code creates the desired_dict default structure. Then I loop through the current_dict and check whether 'TP' and class name match to update the desired_dict default structure (something like this):

for k1,v1 in current_dict.items():
    for k2, v2 in v1.items():
        if k1 == 'TP' and v2=='class_A':
            desired_dict['class_A']['TP'].update(v2)

This is very inefficient as I would need to create many if statements to match class and count type. Any ideas on efficient ways to get the desired_dict? Is there a way to group these by classes A, B, C?

>Solution :

Does this achieve what you want?

from pprint import pprint

current_dict = {'TP': {'class_A': 100,
                       'class_B': 200,
                       'class_C': 300},
                'FP' : {'class_A': 50,
                       'class_B': 60,
                       'class_C': 70},
                'FN' : {'class_A': 10,
                       'class_B': 20,
                       'class_C': 30}
                }

rearranged_dict = {}
# k is TP, FP, FN
for k, v in current_dict.items():
    # c is class_A, class_B
    for c, value in v.items():
        rearranged_dict.setdefault(c, {})[k] = value


pprint(rearranged_dict)

Output:

{'class_A': {'FN': 10, 'FP': 50, 'TP': 100},
 'class_B': {'FN': 20, 'FP': 60, 'TP': 200},
 'class_C': {'FN': 30, 'FP': 70, 'TP': 300}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading