import re


def translate_dict(cmd_list, label_map, dict_key='label'):
    """Create a translate dictionary of labels
    
    Parameters
    ----------
    cmd_list : list of dict
        The Benchpress commands to translate
    label_map : dict
        Dictionary mapping old to new labels: {'old_label': 'new_label'}. 
    dict_key
        The dict-key in the command to translate. 

    Returns
    -------
    new_cmd_list : list of dict 
        Copy of `cmd_list` sorted in the same order as `label_map`
    dictionary : dict
        Dictionary mapping old to new labels of ALL commands in 'cmd_list'
    """
    cmd_list = list(cmd_list)  # We need a copy since we pop items as we go
    ret_map = {}
    ret_list = []
    if label_map is not None:
        for (old, new) in label_map:
            if len(new) > 0:
                for i in range(len(cmd_list)):
                    if re.search(old, cmd_list[i][dict_key]) is not None:
                        ret_map[cmd_list[i][dict_key]] = new
                        ret_list.append(cmd_list[i])
                        cmd_list.pop(i)
                        break
    for old, new in [(t, t) for t in cmd_list]:
        ret_map[old[dict_key]] = new[dict_key]
        ret_list.append(old)
    return ret_list, ret_map