
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 −
Example
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[0]) 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))
Output
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)]
Explanation
- 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.
- Related Articles
- 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 program to Order Tuples using external List
- Python - Insert list in another list
- Python program to mask a list using values from another list
- Finding frequency in list of tuples in Python
- Custom sorting in list of tuples in Python
- Python program to find Tuples with positive elements in a List of tuples
- Create a list of tuples from given list having number and its cube in each tuple using Python

Advertisements