Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
