Home > other >  Changing dictionary keys using a separate dictionary?
Changing dictionary keys using a separate dictionary?

Time:03-12

I am using the CIFAR 10 data set and want to create a function which returns the number of images per class. I have a dictionary classes_dict which maps the class name to the value, see below:

classes_dict= {'airplane': 0, 
'automobile': 1, 
'bird': 2, 
'cat': 3, 
'deer': 4, 
'dog': 5, 
'frog': 6, 
'horse': 7, 
'ship': 8, 
'truck': 9}

And a dictionary images_per_class which counts the frequency of each class:

from collections import Counter

img_per_class = Counter(y_train)
img_per_class

Counter({0: 5000,
         1: 5000,
         2: 5000,
         3: 5000,
         4: 5000,
         5: 5000,
         6: 5000,
         7: 5000,
         8: 5000,
         9: 5000})

I want to change the key in images_per_class so it corresponds to the correct class name. Desired output:

{'airplane': 5000,
 'automobile': 5000,
 'bird': 5000,
 'cat': 5000,
 'deer': 5000,
 'dog': 5000,
 'frog': 5000,
 'horse': 5000,
 'ship': 5000,
 'truck': 5000} 

CodePudding user response:

You can use a dict-comprehension.

result = {k: img_per_class[v] for k, v in classes_dict.items()}

(You can pass this dict to the Counter constructor if you must have a Counter.)

  • Related