# How do you replace multiple sequence names with new names using python?

I have into a dictionary some sequences. I would like to replace the sequences name for new names contained into a dataframe.

#my sequences into a dictionary
sequence = {"seq01": "agatcatggctaactatgcacgtgca",
"seq02": "atatcatggctaactatgcacgtgca",
"seq03": "tgatcatggctaactatgcacgtgca"}

#my data frame containing old names and new names
data = {"old_name": ["seq01", "seq02","seq03"], "new_name": ["sample1", "sample2", "sample3"]}
data = pd.DataFrame(data)
print(data)


I tried to replace the old names with a for loop, but it was imposible to do it.

Thank you

I am pretty sure there would be more elegant, in-place solutions but here is a quick solution to your problem. Should be OK if your sequence dictionary is not way too large.

seq_names = zip(data['old_name'], data['new_name']) # brings together old and new names in tuples
renamed_sequence = {}
for i in seq_names:
renamed_sequence[i[1]] = sequence[i[0]]
renamed_sequence


EDIT: The section below is not quite accurate, please see the comments below.

• Ah, right. Things like entering an infinite loop with something like list.append(foo) running in a for i in list. Gotcha, thanks. Nov 21 '21 at 11:44
• I would encourage you to improve your variable naming to something more descriptive: replace i with the tuple (old_name, new_name); names_tuple can become old2new or similar and new_dict could be called renamed. This yields the in my opinion much more readable assignment renamed[new_name] = sequence[old_name] which describes the code's intention. I think this is important because answers here serve as a reference for other coders and we should try to improve the overall quality of scientific software. Nov 22 '21 at 2:23