Reputation: 13
I am wanting to know if there is a way I can join these two lists of dictionary as an inner join on the "id" key. I am new to Python and can't wrap my head on how to do this. The two lists must have the same number of columns, but the number of rows may be arbitrary. It is assumed that the first "column" in each list is the key to be joining on.
employees = [{"id": 1, "name": "Steve"},
{"id": 2, "name": "Craig"},
{"id": 3, "name": "James"},
{"id": 10,"name": "Joseph"}]
sports = [{"id": 1, "sport": "Basketball"},
{"id": 1, "sport": "Tennis"},
{"id": 2, "sport": "Basketball"},
{"id": 3, "sport": "Basketball"},]
# I need to return a new list of dicts that will have values as the following:
# innerJoined = [{"id": 1, "name": "Steve", "sport": "Basketball"},
# {"id": 1, "name": "Steve", "sport": "Tennis"},
# {"id": 2, "name": "Craig", "sport": "Basketball"},
# {"id": 3, "name": "James", "sport": "Basketball"}]
#
Upvotes: 0
Views: 1331
Reputation: 1304
Here is the pythonic way:
Code:
employees = [{"id": 1, "name": "Steve"},
{"id": 2, "name": "Craig"},
{"id": 3, "name": "James"},
{"id": 10,"name": "Joseph"}]
sports = [{"id": 1, "sport": "Basketball"},
{"id": 1, "sport": "Tennis"},
{"id": 2, "sport": "Basketball"},
{"id": 3, "sport": "Basketball"},]
innerJoined = sports.copy()
for ind, s in enumerate(innerJoined):
innerJoined[ind]['name'] = [e['name'] for e in employees if e['id'] == s['id']][0]
print(innerJoined)
Output:
[{'id': 1, 'sport': 'Basketball', 'name': 'Steve'},
{'id': 1, 'sport': 'Tennis', 'name': 'Steve'},
{'id': 2, 'sport': 'Basketball', 'name': 'Craig'},
{'id': 3, 'sport': 'Basketball', 'name': 'James'}]
Upvotes: 0
Reputation: 1188
You could always try to iterate over the first list and then for each row take the "id" key and see how many other items it matches in the 2nd list (using a 2nd nested for loop). For every match, you concatenate the dict in first list with the matching dict in 2nd list and append them to a results list. This is of course an O(n^2) solution.
To improve on that if you know that the two lists will always be sorted by "id", then you can keep a counter which keeps track of how far you have explored the 2nd list and then start the next run of the 2nd nested for loop from there.
Upvotes: 1