I have the following problem. I want to compare two lists with dictionaries and find matches.
Schema List A:
[
{
authorID: string,
articleID: string
}
]
Schema List B:
[
{
authorID: string,
firstName: string,
lastName: string
}
]
The length of the list A is 1653 and the list B is 1344 long.
This is my code with which I tried to compare the lists and resave the matches.
def unitedListArticleAuthor(listA, listB):
new_list = []
for article in listA:
for author in listB:
if article["authorID"] == author["authorID"]:
new_list.append({
"articleID": article["articleID"],
"authorID": article["authorID"],
"firstName": author["firstName"],
"lastName": author["lastName"],
})
Now the length of the new list is 1667. That means somewhere a mistake must have happened, because the list A is the biggest and only has to be matched with the list B. Only the author ID's should be matched to add the name of the author to each article.
What is my mistake?
CodePudding user response:
As Sayse said, it is likely that there are multiple instances of the same authorID.
You seem really sure that this is not the case, but try adding a break
statement like this:
def unitedListArticleAuthor(listA, listB):
new_list = []
for article in listA:
for author in listB:
if article["authorID"] == author["authorID"]:
new_list.append({
"articleID": article["articleID"],
"authorID": article["authorID"],
"firstName": author["firstName"],
"lastName": author["lastName"],
})
break