0
id_dict = {1 : 'cat', 2 : 'dog', 3 : 'fish', 4 : 'cow' }
feature_list = ['cat','cat', 'dog', 'dog','fish', 'calf']
id_list = ['nan','nan','nan','nan','nan', 'nan']

for key, value in id_dict.items():
    for item in feature_list:
        if item == value:
            id_list[feature_list.index(value)] = key

How can I make sure that the id_list is updated with [1,1,2,2,3] when the values match and pass over when a value is not in there ? Currently, only the first value is being updated. Current Output: [1, 'nan', 2, 'nan', 3]

NoobPythoner
  • 87
  • 10

1 Answers1

1

Your id_dict is backwards of what is useful for you:

id_dict = {1 : 'cat', 2 : 'dog', 3 : 'fish' }
feature_list = ['cat','cat', 'dog', 'dog','fish']
# id_list = ['nan','nan','nan','nan','nan']

# Swap the keys and values (ideally change the starting dictionary)
id_dict = {val: key for key, val in id_dict.items()}

# Create your id_list
id_list = [id_dict[ele] for ele in feature_list]

If you need to handle values that are not in id_dict then you have several different options.

To apply a default:

id_list = [id_dict.get(ele, 'Default value') for ele in feature_list]

If you want to skip values that are not contained within id_dict:

id_list = [id_dict[ele] for ele in feature_list if ele in id_dict]