Question: This is `table1` in SQL Server:

```
Last   Country   colA   colB   colC
------------------------------------
1      ARG       NA     NA     NA
2      NULL      NA     NA     NA
3      CAM       NA     NA     NA
4      NULL      NA     NA     NA
5      NULL      NA     NA     NA

```

This is my dataframe `DF` in R:

```
colA   colB   colc
20     foo    1.2
12     bar    12.2
1      tam    10.3
15     red    0.8

```

Now how do I iterate for every row in `DF` so that it could be updated in `table1`?

This is the code in r

```
conn <- odbcDriverConnect('DRIVER={SQL Server};SERVER=dusty;DATABASE=Area;UID=admin;PWD=abcd@123;autocommit=True')
data <- sqlQuery(conn,paste("select * from table1;"))
for(i in 1:length(DF)) {
update.query <- paste("UPDATE table1 ", 
                       "SET colA=?",
                       "SET colB=?",
                       "SET colC=?",
                       "WHERE Country is NULL", sep="")
dummy <- sqlQuery(conn, update.query)
}

```

Any suggestions how it could be done?

Thanks.

Answer: 
You can use the builtin `max` function and provide a matching key:

```
# The input to search over
l = [{'a':''}, {'a':'', 'b':''}, {'a':'','b':'','c':''}]
# Extract the keys we'd like to search for
t = set({'a': '', 'c': ''}.keys())

# Find the item in l that shares maximum number of keys with the requested item
match = max(l, key=lambda item: len(t & set(item.keys())))

```

To extract the index in one pass:

```
max_index = max(enumerate(l), key=lambda item: len(t & set(item[1].keys())))[0]

```
```
>>> lst  = [{'a':'a'},{'a':'a','b':'b'},{'a':'a','b':'b','c':'c'}]
>>> seen = {}
>>> [seen.update({key:value}) for dct in lst  for key,value in dict(dct).items() if key not in seen.keys()]

>>> seen

```

**Output**

```
{'a': 'a', 'c': 'c', 'b': 'b'}

```

[check here](https://repl.it/KQ2j/0)