How to iterate through duplicates from a reverse dictionary to a list

Viewed 19

I want to be able to reverse the list with a set of values in a dictionary. However some of the values are duplicates and when its brought into reversing the list, it only uses the same value.

my_list = (1, 2, 3, 3, 4)

my_dict = {'Apple': 1, 'Orange': 2, 'Banana': 3, 'Kiwi': 3, 'Pear': 4}

I have it so that if I want the list to be saying the fruits, it will reverse the dictionary and print out the fruits

new_list = []
for a in my_list:
  reversed_dict = {my_dict[k]:k for k in my_dict}
  fruit = [reversed_dict[elem] for elem in a]
  new_list.append(fruit)

This will print out the list as: [Apple, Orange, Kiwi, Kiwi, Pear)

I want it to be able to check for duplicates and since 3 is in the list twice, if the same option (Kiwi) has already been said, then switch it to the other key in the dictionary. So ideally it would show.

This will print out the list as: [Apple, Orange, Banana, Kiwi, Pear)

1 Answers

We know all of the keys in the dictionary are unique. Therefore, we can iterate over the dictionary and just check if the value is in my_list.

for (key, value) in my_dict.items():
    if value in my_list:
         print(key)

May or may not be relevant but if your my_dict is large, you'll want to convert my_list to a set for better performance when checking if the value is in my_list.

my_set = set(my_list)
Related