Program to convert a list of tuples in a dictionary

In this python tuple program, we will convert a list of tuples in a dictionary.

Steps to solve the program
  1. Take a list of tuples as input and create an empty dictionary.
  2. Use for loop to iterate over each tuple in the list.
  3. Use D.setdefault(a, []).append(b) it will set the first value in the tuple as the key and create an empty list to store its values.
  4. a is the key and b is the valueis the name of the dictionary.
  5. If there is a tuple in the list whose key has been previously used then it will not create a new key-value pair instead it will add the value of the tuple to the existing list of key-value pair.
  6. Print the output.
				
					l =  [('s',2),('q',1),('a',1),('s',3),('q',2),('a',4)]
print("List of tuples: ",l)
D = {}
for a, b in l:
    D.setdefault(a, []).append(b)

print("Dictionary: ",D)
				
			

Output :

				
					List of tuples:  [('s', 2), ('q', 1), ('a', 1), ('s', 3), ('q', 2), ('a', 4)]
Dictionary:  {'s': [2, 3], 'q': [1, 2], 'a': [1, 4]}
				
			

program to reverse a tuple.

Leave a Comment