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

Using list to iterate over dictionary

I have a list ‘labels’ and a dictionary with key, value pairs ‘class_dict’.

I want to loop over my labels list, and print the dictionary key (e.g. ‘airplane’), if the class_dict.value() is equal to the label[i].

labels = [2, 7, 1, 0, 3, 2, 0, 5, 1, 6, 3, 4, 2, 9, 3, 8]

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

For example

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

labels[0] = 'bird'
labels[1] = 'ship'
labels[2] = 'automobile'

Essentially I want to do this but in a more concise way:

for i in labels:
  for key, val in classes_dict.items():
    if val == i:
      print(key)

>Solution :

You could for example swap key and value of the dict and then simply access it with the list elements:

reversed_dict = {value: key for key, value in class_dict.items()}
new_list = [reversed_dict[x] for x in labels]

print(new_list)

Output:

['bird', 'horse', 'automobile', 'airplane', 'cat', 'bird', 'airplane', 'dog', 'automobile', 'frog', 'cat', 'deer', 'bird', 'truck', 'cat', 'ship']
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