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:


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]

    return inverse


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
        reversed_d[v] = k


output :