'assign value for matching items in different sublists in Python
I have 3 lists, each with 2 sublists. The items in the sublists of list 1 is leading. The lists 2 and 3 have two sublists too, each with the same number of items, but a different of items than list1.
I want to retrieve the value of the item in the sublists of list 3 for which the item in sublist of list 1 matches an item in the same sublists of list 2.
example:
list1 = [['857917', '874263', 'noot', '874263', '857917'],['noot', 'mies']]
list2 = [['857917', '957921', '857923', '874263', '874265', '874267', '875241'],['klaas', 'mies', 'noot']]
list3 = [['house', 'car', 'bike', 'chair', 'table', 'bed', 'kitchen'],['plane', 'boat', 'motor']]
the result should be: [['house', 'chair', null, 'chair', 'house'],['motor', 'boat']]
so in the example above, 857917 from the 1st sublists of list1 matches the same number in the 1st sublist from list2 and should return "house" from list3
"noot" from the 2nd sublist from list 1 should return "motor" from the 2nd sublist from list 3
BUT: "noot" from the 1st sublist from list 1 should return null since it is not appearing in the first sublist of list2.
I hope that someone can help me on this. Thanks
Solution 1:[1]
IIUC, you could zip the three lists and build a dictionary from the second and third lists to map the values from the first one:
out = []
for A,B,C in zip(list1, list2, list3):
d = dict(zip(B,C))
out.append([d.get(a, None) for a in A])
output:
[['house', 'chair', None, 'chair', 'house'], ['motor', 'boat']]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozway |
