vendredi 29 janvier 2021

What is faster: adding a key-value pair or checking for the existence of a key?

Imagine a CSV file with 3 columns: individual name, group name, group ID. Obviously column 1 is different for every line while column 2 and 3 can be the same as before (every group name has an individual ID though). This is not sorted in any way.

For reasons I'm creating a dict to save: group ID (key) --> group name (value). Now what is faster of the following variants?

  1. checking if that key already exists and only saving if not.

    if ID not in group_dict:
       group_dict[ID] = name 
    
  2. just saving it every time again (replacing the value, which is the same anyway).

    group_dict[ID] = name 
    

Aucun commentaire:

Enregistrer un commentaire