Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a list of lists as a lookup table and updating a value in new list of lists

Tags:

I have an application that creates a list of lists. The second element in the list needs to be assigned using lookup list which also consists of a list of lists.

I have used the "all" method to match the values in the list. If the list value exists in the lookup list, it should update the second position element in the new list. However this is not the case. The == comparative yields a False match for all elements, even though they all exist in both lists.

I have also tried various combinations of index finding commands but they are not able to unpack the values of each list.

My code is below. The goal is to replace the "xxx" values in the newData with the numbers in the lookupList.

lookupList= [['Garry','34'],['Simon', '24'] ,['Louise','13'] ]

newData = [['Louise','xxx'],['Garry', 'xxx'] ,['Simon','xxx'] ]  

#Matching values
for i in newData: 
    if (all(i[0] == elem[0] for elem in lookupList)):
        i[1] = elem[1]
like image 358
alkey Avatar asked Aug 22 '16 16:08

alkey


1 Answers

You can't do what you want with all(), because elem is not a local variable outside of the generator expression.

Instead of using a list, use a dictionary to store the lookupList:

lookupDict = dict(lookupList)

and looking up matches is a simple constant-time (fast) lookup:

for entry in newData:
    if entry[0] in lookupDict:
        entry[1] = lookupDict[entry[0]]
like image 119
Martijn Pieters Avatar answered Sep 22 '22 17:09

Martijn Pieters