Home > Enterprise >  Using list to iterate over dictionary
Using list to iterate over dictionary

Time:03-09

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

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)

CodePudding user response:

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']

CodePudding user response:

please note that your dictionnary is reversed, so think about reverse it first

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}
new_dict = {v: k for k, v in class_dict.items()}

for l in labels:
    print(new_dict[l])
  • Related