Search code examples
pythonlistdictionarytuples

A list of tuples from dictionary where values are lists


I need to convert a dictionary in a form {1: ['a', 'b', 'c', 'd'], 2: ['e', 'f', 'g', 'h']} to a list of tuples in a form [(1, 'a', 'b', 'c', 'd'), (2, 'e', 'f', 'g', 'h')].

When I try that:

dictionary = {1: ['a', 'b', 'c', 'd'], 2: ['e', 'f', 'g', 'h']}

list_of_tuples = [(k, v) for k, v in dictionary.items()]

I get

list_of_tuples = [(1, ['a', 'b', 'c', 'd']), (2, ['e', 'f', 'g', 'h'])]

and I need

list_of_tuples = [(1, 'a', 'b', 'c', 'd'), (2, 'e', 'f', 'g', 'h')]

Solution

  • Try

    list_of_tuples = [(k, *v) for k, v in dictionary.items()]
    

    *v unpacks v.