-1

I want to find nonunique values in the original dictionary and store the keys associated with the value in a list. then store the nonunique value as a key and the list of keys as a value in a new dictionary.

Example:

    >>> invert({'one':1, 'two':2,  'three':3, 'four':4}) #Input
    {1: 'one', 2: 'two', 3: 'three', 4: 'four'} #output
    >>> invert({'one':1, 'two':2, 'uno':1, 'dos':2, 'three':3}) #input
    {1: ['one', 'uno'], 2: ['two', 'dos'], 3: 'three'} #output
    >>> invert({'123-456-78':'Sara', '987-12-585':'Alex', '258715':'sara', '00000':'Alex'}) 
    {'Sara': '123-456-78', 'Alex': ['987-12-585', '00000'], 'sara': '258715'}
def invert(d):

    pass

    inverted_dict = {}
    non_unique_lst = []

    for key,value in d.items() :

        if  value in inverted_dict:

            non_unique_lst = [key]
            inverted_dict[value,non_unique_lst]
            print (non_unique_lst)
            
        else:

            inverted_dict[value] = key
       
    print (inverted_dict)
    return inverted_dict
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Toodles
  • 9
  • 3

1 Answers1

0

I think this does what you want with the addition of handling more than 2 items. It maintains individual items when there is only one value, but converts to a list when there are 2 or more.

def invert(d):
    inverted_dict = {}

    for key, value in d.items():

        existing = inverted_dict.get(value, None)

        # if it is already a list append
        if isinstance(existing, list):
            inverted_dict[value].append(key)

        # if it is existing but not a list make a list
        elif existing:
            inverted_dict[value] = [existing, key]

        # if it doesn't exist add it
        else:
            inverted_dict[value] = key
    return inverted_dict
ak_slick
  • 1,006
  • 6
  • 19
  • in there a way to do this without any functions apart from appending? I can't use the .get function – Toodles Sep 02 '22 at 22:44
  • .get is a built in of a dictionary it should work. I believe you will always end up building a list if you have multiple values. Why do you not want to append? if you want to avoid .get you could use if value in inverted_dict.keys(). I think there is another way to do it but I do not know it off the top of my head. – ak_slick Sep 06 '22 at 17:07