Python | Convert Lists to Column Tuples

Python Methods and Functions

Method # 1: Using zip () + comprehension list
A combination of the above functions can work together to accomplish this particular task. In this, we concatenate similar index items into a column using zip () and concatenate all tuples into a list, and iterate over the dictionary lists by comprehending the list.

# Python3 code to demonstrate how it works
# Convert lists to column tuples
# using zip () + comprehension list

 
# initialize dictionary

test_dict = { 'list1 ' : [ 1 , 4 , 5 ], 

'list2' : [ 6 , 7 , 4 ],

'list3' : [ 9 , 1 , 11 ]}

  
# printing the original dictionary

print ( " The original dictionary is: " + str (test_dict))

 
# Convert lists to column tuples
  # using zip () + list comprehension

res = list ( zip ( * (test_dict [key] for key in test_dict.keys ())))

 
# print result

print ( "Like index column tuples are:" + str (res))

Output:

The original dictionary is: {'list3': [9, 1, 11], 'list2': [6, 7 , 4], 'list1': [1, 4, 5]}
Like index column tuples are: [(9, 6, 1), (1, 7, 4), (11, 4, 5)]

Method # 2: Using zip () + values ​​()
A combination of the above functions can be used to accomplish this task. In doing so, we access the values ​​of the dictionary values ​​using values ​​() and the aggregating columns can be done using zip () .

# Python3 code to demonstrate how it works
# Convert lists to column tuples
# using zip () + values ​​()

 
# initialize dictionary

test_dict = { 'list1' : [ 1 , 4 , 5 ], 

' list2' : [ 6 , 7 , 4 ], 

'list3' : [ 9 , 1 , 11 ]}

 
# printing the original dictionary

print ( "The original dictionary is:" + str (test_dict))

  
# Convert lists to column tuples
# using zip () + values ​​()

res = list ( zip ( * test_dict.values ​​()))

 
# print result

print ( "Like index column tuples are:" + str (res))

Exit:

The original dictionary is: {'list3': [9, 1, 11], 'list2': [6, 7, 4], 'list1': [1, 4, 5]}
Like index column tuples are: [(9, 6, 1), (1, 7, 4), (11, 4, 5)]





Get Solution for free from DataCamp guru