Search code examples
pythonlistloopsiterationnested-loops

How to loop through two list of lists at once and replace values from one list with the other list?


I have two lists of lists (a and b)

They both have only 2 indexes per row.

a (50,000 rows) looks like this:

|name|age|
|----|---|
|Dany|021|
|Alex|035|

As a list of lists, looks like this:

[['Dany', '021'],['Alex','035'], etc...]

b (2000 rows) looks like this:

|name|age|
|----|---|
|Paul|   |
|Leon|   |

As a list of lists, looks like this:

[['Paul', ''],['Leon',''], etc...]

Question: I want to iterate through a and b at the same time - for each iteration of a, if a[0] is in b[0], I want to add the corresponding a[1] into b[1].

In lay terms, I want to add ages to my b list by going through my a list, checking if the name is in the a list and if it is, taking that corresponding age and adding it in the b list for that corresponding name.

I have tried a nested loop (iterating through b and for each iteration, iterating through a to check if any iteration of a at a[0] exists in that iteration of b at b[0]) but just keep getting lost after that.

for row in b[1:]: # Excluding the headers
    b_name = row[0]
    b_age = row[1]
    for row in a[1:]:
        if b_name in row[0]:
            b_age = row[1]
        else:
            b_age = ''

The issue is that I end up getting just one value for b_age, but there should be 2000 unique b_age values?


Solution

  • Assuming the names in a are unique, you could create a dict from a to avoid looping through it over and over as you replace the empty string values in b. For example (added a couple items to your examples to illustrate what would happen if a name in b does not exist in a):

    a = [['Dany', '021'], ['Alex','035'], ['Joe', '054']]
    b = [['Alex',''], ['Dany', ''], ['Jane', '']]
    
    d = {k: v for k, v in a}
    b = [[k, d[k]] if k in d else [k, v] for k, v in b]
    print(b)
    # [['Alex', '035'], ['Dany', '021'], ['Jane', '']]
    

    If the list you are actually working with is just a simple list of pairs as in the example, then you could replace the dict comprehension above with dict(a).

    Also, in case it is not clear, the various k, v references are for convenience in unpacking the nested pairs, but you could just use a single variable and access using index values like:

    {x[0]: x[1] for x in a}