In this python tuple program, we will convert a list of tuples in a dictionary.
Steps to solve the program
- Take a list of tuples as input and create an empty dictionary.
- Use for loop to iterate over each tuple in the list.
- 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.
- a is the key and b is the value, D is the name of the dictionary.
- 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.
- 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.