Python3: Create a datatype based dictionary from a list with generic datatypes include their values

avatar
# TASK: Create a datatype based dictionary from a list with generic datatypes include their values
# Input: List of any datatypes
# Output : dictionary with a key as datatype and value with their associated values
#
# Example:
# Input: [1,2,3,'a','b','c',False]
# Output: { int : [1,2,3], str : ['a,'b','c'], bool : [False]}

def datatypeSeperator():
    original: list[any] = [5, [1, 2, 3], -1, True, 7, 'tower', None, False, False, {3, 3, 5, 5}, 'cloud', 3,
         'taxi', {'a': 1,'b': 2}, 3.5, {'a': -7}, None, [5, 6], -11.565,
         int('7'), -6, True, Exception('error')]

    sorted_datatypes: dict = {}

    # for each element from the original list of any
    for elem in original:
        # datatype and his value(s) are not included yet
        if sorted_datatypes.get(type(elem)) is None:
            sorted_datatypes.update({type(elem): [elem]})

        # datatype already in the dictionary, update the value(s)
        else:
            values = sorted_datatypes.get(type(elem))
            values.append(elem)
            sorted_datatypes.update({type(elem): values})

    for k, v in sorted_datatypes.items():
        print(k, ' => ', v)


if __name__ == '__main__':
    datatypeSeperator()



0
0
0.000
0 comments