Python | Update a list of tuples using another list
Last Updated :
18 Apr, 2023
Given two list of tuples, write a Python program to update ‘list1’ according to the ‘list2’ and return an updated list.
Examples:
Input : list1 = [('x', 0), ('y', 5)]
list2 = [('x', 100), ('y', 200)]
Output : [('x', 100), ('y', 200)]
Input : list1 = [('a', 0), ('b', 0), ('c', 0)]
list2 = [('a', 1), ('b', 2)]
Output :[('a', 1), ('b', 2), ('c', 0)]
Approach #1 Pythonic Naive This is a Pythonic naive approach. We simply convert the list of tuples into a dictionary and just update it with list2 and convert the dictionary back to list.
Python3
def merge(list1, list2):
dic = dict (list1)
dic.update( dict (list2))
return list (dic.items())
list1 = [( 'a' , 0 ), ( 'b' , 0 ), ( 'c' , 0 )]
list2 = [( 'a' , 5 ), ( 'c' , 3 )]
print (merge(list1, list2))
|
Output
[('a', 5), ('b', 0), ('c', 3)]
Time complexity: O(n*n) as it uses nested loop to check each element of list2 with the elements of output list.
Auxiliary space: O(n) as it uses a separate list to store the combined elements without duplicates.
Approach #2 Using defaultdict Python collections module provides defaultdict() method which is used in this approach. First we initialize ‘dic’ with defaultdict method passing list as factory. Use a loop to append the left element of each tuple as key and right element of each tuple as value for both the lists. Now simply use the sorted function and produce the list in such a way that the for each unique key it keeps the maximum value of right element of tuple.
Python3
from collections import defaultdict
def merge(list1, list2):
dic = defaultdict( list )
for i, j in list1 + list2:
dic[i].append(j)
return sorted ([(i, max (j)) for i, j in dic.items()],
key = lambda x:x[ 0 ])
list1 = [( 'a' , 0 ), ( 'b' , 0 ), ( 'c' , 0 )]
list2 = [( 'a' , 5 ), ( 'c' , 3 )]
print (merge(list1, list2))
|
Output
[('a', 5), ('b', 0), ('c', 3)]
Approach #3: Using simple iteration:
Python3
def merge(list1, list2):
dic = {}
for key, value in list1 + list2:
dic[key] = value
return list (dic.items())
list1 = [( 'x' , 0 ), ( 'y' , 5 )]
list2 = [( 'x' , 100 ), ( 'y' , 200 )]
print (merge(list1, list2))
|
Output
[('x', 100), ('y', 200)]
This code defines a function merge that takes in two lists of tuples list1 and list2. The function creates an empty dictionary dic. It then iterates over the tuples in list1 and list2 and adds them to the dictionary dic as key-value pairs. The function then returns a list of tuples representing the key-value pairs in the dictionary dic.
The time complexity of this code is O(n) where n is the total number of tuples in list1 and list2. This is because the function iterates over each tuple in the lists once. The space complexity of this code is also O(n) as the dictionary dic will store n key-value pairs.
When the code is run with the given input, it will print [(‘x’, 100), (‘y’, 200)].
Approach#4: Using list
this approach uses a list comprehension to iterate through list2 and either replace the value in list1 if the key exists or append the key-value tuple to list1 if the key does not exist.
Algorithm
1. Iterate through list2 and check if the key exists in list1.
2. If the key exists, replace the value in list1.
3. If the key does not exist, append the key-value tuple to list1.
4. Return list1.
Python3
def update_list_of_tuples_using_list_comprehension(list1, list2):
for key, value in list2:
for i in range ( len (list1)):
if list1[i][ 0 ] = = key:
list1[i] = (key, value)
break
else :
list1.append((key, value))
return list1
list1 = [( 'x' , 0 ), ( 'y' , 5 )]
list2 = [( 'x' , 100 ), ( 'y' , 200 )]
print (update_list_of_tuples_using_list_comprehension(list1, list2))
|
Output
[('x', 100), ('y', 200)]
Time Complexity: O(n*m) where n is the length of list1 and m is the length of list2.
Space Complexity: O(1)
Similar Reads
Python - Create list of tuples using for loop
In this article, we will discuss how to create a List of Tuples using for loop in Python. Let's suppose we have a list and we want a create a list of tuples from that list where every element of the tuple will contain the list element and its corresponding index. Method 1: Using For loop with append
2 min read
Convert Tuple Value List to List of Tuples - Python
We are given a dictionary with values as a list of tuples and our task is to convert it into a list of tuples where each tuple consists of a key and its corresponding value. Note: Each key will appear with each value from the list of tuples. For example: We have a dictionary dict = {'Gfg' : [(5, ),
4 min read
Python - Convert List of Lists to Tuple of Tuples
Sometimes, while working with Python data, we can have a problem in which we need to perform interconversion of data types. This kind of problem can occur in domains in which we need to get data in particular formats such as Machine Learning. Let us discuss certain ways in which this task can be per
8 min read
Python | Update each element in tuple list
The task of updating each element in a tuple list in Python involves adding a specific value to every element within each tuple in a list of tuples. This is commonly needed when adjusting numerical data stored in a structured format like tuples inside lists. For example, given a = [(1, 3, 4), (2, 4,
4 min read
Python | Unpacking tuple of lists
Given a tuple of lists, write a Python program to unpack the elements of the lists that are packed inside the given tuple. Examples: Input : (['a', 'apple'], ['b', 'ball']) Output : ['a', 'apple', 'b', 'ball'] Input : ([1, 'sam', 75], [2, 'bob', 39], [3, 'Kate', 87]) Output : [1, 'sam', 75, 2, 'bob'
3 min read
Python - Convert a list into tuple of lists
When working with data structures in Python, there are times when we need to convert a list into a tuple of smaller lists. For example, given a list [1, 2, 3, 4, 5, 6], we may want to split it into a tuple of two lists like ([1, 2, 3], [4, 5, 6]). We will explore different methods to achieve this co
3 min read
Python | Convert list of tuples into list
In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
3 min read
Python | Combining tuples in list of tuples
Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways
7 min read
Swap tuple elements in list of tuples - Python
The task of swapping tuple elements in a list of tuples in Python involves exchanging the positions of elements within each tuple while maintaining the list structure. Given a list of tuples, the goal is to swap the first and second elements in every tuple. For example, with a = [(3, 4), (6, 5), (7,
3 min read
Convert Set of Tuples to a List of Lists in Python
Sets and lists are two basic data structures in programming that have distinct uses. It is sometimes necessary to transform a collection of tuples into a list of lists. Each tuple is converted into a list throughout this procedure, and these lists are subsequently compiled into a single, bigger list
3 min read