unim192745
unim192745

Reputation: 79

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

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)

Upvotes: 2

Views: 157

Answers (3)

Sayse
Sayse

Reputation: 43320

Assuming the values are always sequential starting from 0 and increasing you can just get the keys and do a normal look up

class_keys = class_dict.keys()
labels = [class_keys[i] for i in labels]

Upvotes: 1

Moun
Moun

Reputation: 315

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

Upvotes: 1

JANO
JANO

Reputation: 3076

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

Upvotes: 4

Related Questions