Python program to convert list of tuples to dictionary value lists

One among the problem of interconversion of data types in python is conversion of list of tuples to dictionaries, in which the keys are 1st element of tuple, which are uniquely identified as keys in dictionary and it’s corresponding value as list of corresponding value of respective keys as tuple’s second element. Let’s discuss how to solve this particular problem.

Python program to convert a list of tuples into a dictionary where the keys are the first elements of the tuples and the values are lists of the second elements of the tuples: 

 

def tuples_to_dict_value_lists(lst):
    """
    Converts a list of tuples into a dictionary where the keys are the first elements of the tuples
    and the values are lists of the second elements of the tuples.
    
    :param lst: A list of tuples
    :type lst: list
    :return: A dictionary with key-value pairs
    :rtype: dict
    """
    dict = {}
    for tup in lst:
        key = tup[0]
        val = tup[1]
        if key not in dict:
            dict[key] = [val]
        else:
            dict[key].append(val)
    return dict

Here's an example usage of the above function: 

 

lst = [("a", 1), ("b", 2), ("a", 3), ("c", 4)]
result = tuples_to_dict_value_lists(lst)
print(result)

This would output the following dictionary: 

 

{'a': [1, 3], 'b': [2], 'c': [4]}

I hope this helps! Let me know if you have any questions.

Submit Your Programming Assignment Details