Reversing dictionary is separating string characters in Python

I am trying to create a dictionary with key-value pairs identical:

d = {'SEX': 'SEX', 'F': 'F', 'M': 'M', 'U': 'U', 'UNDIFFERENTIATED': 'UNDIFFERENTIATED'}

Eventually, it will have additional values associated with keys (i.e., 'M': ['M','MALE']), but I am starting with the simplest case above first.

I next need to reverse the dictionary. For the simple example d, d=reverse_d. In the future with 'M': ['M','MALE'], I would get 'M':'M', 'MALE':'M'.

When I try to reverse the simple case of d; however, I get the individual characters of values in the dictionary creating separate keys:

reverse_d = {'S': ['SEX'], 'E': ['SEX', 'UNDIFFERENTIATED', 'UNDIFFERENTIATED', 'UNDIFFERENTIATED'], 'X': ['SEX'], 'F': ['F', 'UNDIFFERENTIATED', 'UNDIFFERENTIATED'], 'M': ['M'], 'U': ['U', 'UNDIFFERENTIATED'], 'N': ['UNDIFFERENTIATED', 'UNDIFFERENTIATED'], 'D': ['UNDIFFERENTIATED', 'UNDIFFERENTIATED'], 'I': ['UNDIFFERENTIATED', 'UNDIFFERENTIATED'], 'R': ['UNDIFFERENTIATED'], 'T': ['UNDIFFERENTIATED', 'UNDIFFERENTIATED'], 'A': ['UNDIFFERENTIATED']}

Here is the code I used to reverse it:

def invert_dict(d):
    inverse = dict()

    for key in d:
        for item in d[key]:
            if item not in inverse:
                inverse[item] = [key]
            else:
                inverse[item].append(key)

    return inverse

Answer

you have to check if the value is a list then get the items otherwise you will get characters:

d = {'SEX': 'SEX', 'F': 'F', 'M': ['M', 'MALE'], 'U': 'U', 'UNDIFFERENTIATED': 'UNDIFFERENTIATED'}

reversed_d = {}
for k, v in d.items():
    if isinstance(v, list):
        for item in v:
            reversed_d[item] = k
    else:
        reversed_d[v] = k

print(reversed_d)

output :

{'SEX': 'SEX', 'F': 'F', 'M': 'M', 'MALE': 'M', 'U': 'U', 'UNDIFFERENTIATED': 'UNDIFFERENTIATED'}