Search code examples
pythonpython-3.xdata-structurestuplespython-itertools

Problems while trying to replace a list of tuples?


I have the following lists of tuples:

list1 = [('the', 'a'), ('over','1'), ('quick','b'),('fox', 'c'), ('brown', 'd'), ('dog','e'), ('jumps','2')]

I am trying to replace some tuples as follows (*):

('the', 'a') -> ('the', 'ART')
('quick','b') -> ('quick','VERB')
('fox', 'c') -> ('fox', 'ANIMAL')

In other words, the tuples of list1, should be replaced like this:

list1 = [('the', 'ART'), ('over','1'), ('quick','VERB'),('fox', 'ANIMAL'), ('brown', 'd'), ('dog','e'), ('jumps','2')]

So, I tried with the following function:

def replace_val(alist, key, value):
    return [(k,v) if (k != key) else (key, value) for (k, v) in alist]

The problem is that I can't pass all the new tuples from (*) in one movement, I must do:

replace_val(list1, 'the', 'ART')
replace_val(list1, 'quick', 'VERB')
replace_val(list1, 'fox', 'ANIMAL')

Thus, my question is: How can I replace efficiently in one movement all the new tuples from (*) in order to get?:

[('the', 'ART'), ('over','1'), ('quick','VERB'),('fox', 'ANIMAL'), ('brown', 'd'), ('dog','e'), ('jumps','2')]

Solution

  • I think this would help.

    list1 = [('the', 'a'), ('over','1'), ('quick','b'),('fox', 'c'), ('brown', 'd'), ('dog','e'), ('jumps','2')]
    list2 = [('the', 'a'), ('over','1'), ('quick','b'),('fox', 'c'), ('brown', 'Dog'), ('dog','e'), ('jumps','2')]
    z=(dict(dict(list1),**dict(list2)).items())
    print(z)
    

    DEMO