Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Python left outer join using FOR/LIST/DICTIONARY comprehensions (not SQL)?

I have two tuples, details below:

t1 = [
['aa'],
['ff'],
['er']
]

t2 = [
['aa', 11,],
['er', 99,]
]

and I would like to get results like these below using python method similar to SQL's LEFT OUTER JOIN:

res = [
['aa', 11,],
['ff',  0,],
['er', 99,]
]

Please help me with this.

like image 810
constantine Avatar asked Feb 26 '13 20:02

constantine


People also ask

How to do a LEFT OUTER JOIN in Python?

Left outer Join or Left join pandas: Return all rows from the left table, and any rows with matching keys from the right table.When there is no Matching from right table NaN will be returned # left join in python left_join_df= pd.merge(df1, df2, on='Customer_id', how='left') left_join_df the resultant data frame df will be

How to use the outer join of SQL?

To use this types of the outer join of SQL, you have to use the two tables. The first table is the main table from where you have to take all the rows for the matching columns. Now, find all the values of the selected columns in the SQL query.

How to create a dictionary in Python?

Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions. Let’s see a example,lets assume we have two lists named keys and value now, We can use Dictionary comprehensions with if and else statements and with other expressions too.

What is list comprehension in Python?

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name. Without list comprehension you will have to write a for statement with a conditional test inside:


1 Answers

d2 = dict(t2)
res = [[k[0], d2.get(k[0], 0)] for k in t1]
like image 98
Daniel Roseman Avatar answered Oct 14 '22 01:10

Daniel Roseman