- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Update a list of tuples using another list in Python
When it is required to update a list of tuple using another list, the 'defaultdict' can be used.
Defaultdict is a container similar to dictionaries which is present in 'collections' module. It is a sub-class of the 'dict' class. It returns a dictionary-like object. The 'defaultdict' doesn't raise a KeyError ever. It provides a default value for the key which doesn't exist.
Below is a demonstration for the same −
from collections import defaultdict def merge_vals(list_1, list_2): my_dict = defaultdict(list) for i, j in list_1 + list_2: my_dict[i].append(j) return sorted([(i, max(j)) for i, j in my_dict.items()], key = lambda x:x) my_list_1 = [('v', 1), ('q', 2), ('o', 0)] my_list_2 = [('q', 5), ('o', 3)] print("The first list of tuple is : ") print(my_list_1) print("The second list of tuple is : ") print(my_list_2) print("After merging, it becomes : ") print(merge_vals(my_list_1, my_list_2))
The first list of tuple is : [('v', 1), ('q', 2), ('o', 0)] The second list of tuple is : [('q', 5), ('o', 3)] After merging, it becomes : [('o', 3), ('q', 5), ('v', 1)]
- The required libraries are imported.
- A method named 'merge_vals' is defined, that takes two lists as arguments. A defaultdict is created.
- The elements in the lists are iterated, and the element of the first list is taken as index, and the element from second index is appended to the dictionary.
- This dictionary is sorted and returned.
- Two lists of tuples are created, and displayed on the console.
- The 'merge_vals' method is called by passing these two list of tuples as parameters.
- This is displayed on the console as output.
- Convert list of tuples to list of list in Python
- Convert list of tuples into list in Python
- Combining tuples in list of tuples in Python
- Count tuples occurrence in list of tuples in Python
- Convert list of strings to list of tuples in Python
- Convert list of tuples to list of strings in Python
- Remove duplicate tuples from list of tuples in Python
- Summation of tuples in list in Python
- Python - Insert list in another list
- Python program to mask a list using values from another list
- Python program to Order Tuples using external List
- Finding frequency in list of tuples in Python
- Custom sorting in list of tuples in Python
- Python | Remove empty tuples from a list
- Python program to find Tuples with positive elements in a List of tuples