How to remove duplicate values from dict?

后端 未结 4 1530
星月不相逢
星月不相逢 2020-12-12 01:52

I\'m trying to remove duplicate values in my dict but its not working:

samples_antibiotics_with_duplicates = {\'S00541-09\': [\'Streptomycin\', \'Sulfamethox         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-12 02:23

    There are better ways to do this as seen in the other posts. But to retain as much of your original code as possible while explaining why it doesn't work use this instead:

    samples_antibiotics_with_duplicates = {'S00541-09': ['Streptomycin', 'Sulfamethoxazole', 'Trimethoprim', 'Spectinomycin', 'Streptomycin', 'Streptomycin', 'Trimethoprim']}
    samples_antibiotics = {}
    for key,value in samples_antibiotics_with_duplicates.items():
        samples_antibiotics[key] = set(value)
    print(samples_antibiotics)
    

    The problem is that you iterate through each key in the dictionary in your for loop (so only the 'S00541-09') and then you check if the value is in the values (which obviously it has to be). What I did was essentially iterate the values within the key itself.

提交回复
热议问题