Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: pair matching elements

Tags:

python

I have a the following data structure:

a = [('customerA', '1.0.0'), ('customerB', '1.0.0'), ('customerC', '1.0.1')]
b = (('customerB', '1.1.0'), ('customerC', '1.0.1'))

I want the results to be something like this:

[('customerA', None), ('customerB', '1.0.0', '1.1.0'), ('customerC', '1.0.1', '1.0.1')]

or even skip non existing customers entirely:

[('customerB', '1.0.0', '1.1.0'), ('customerC', '1.0.1', '1.0.1')]

The zip function won't help in this case because b comes from MySQLCursor.fetchall() with WHERE clause for the customer name so it won't match with a if the customer doesn't exist:

>>> [a + (b[1],) for a, b in zip(a, b)]
[('customerA', '1.0.0', '1.1.0'), ('customerB', '1.0.0', '1.0.1')]
>>> import itertools
>>> for a, b in itertools.zip_longest(a, b):
...     print(a, b)
... 
('customerA', '1.0.0') ('customerB', '1.1.0')
('customerB', '1.0.0') ('customerC', '1.0.1')
('customerC', '1.0.1') None
like image 605
HTF Avatar asked Dec 01 '22 14:12

HTF


1 Answers

Have you tried to do it directly?

customers_a = dict(a)
result = [(customer, customers_a[customer], version) for customer, version in b if customer in customers_a]

Now, result is exactly

>>> result
[('customerB', '1.0.0', '1.1.0'), ('customerC', '1.0.1', '1.0.1')]
like image 129
bipll Avatar answered Dec 03 '22 04:12

bipll