Skip to content

Instantly share code, notes, and snippets.

@messa
Created January 13, 2012 23:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save messa/1609425 to your computer and use it in GitHub Desktop.
Save messa/1609425 to your computer and use it in GitHub Desktop.
def connect(*args):
maps = list()
for collection, keyGetter in args:
m = dict()
for item in collection:
key = keyGetter(item)
m[key] = item
maps.append(m)
result = list()
resultKeys = set()
for collection, keyGetter in args:
for item in collection:
key = keyGetter(item)
if key in resultKeys:
continue
resultKeys.add(key)
result.append(tuple(m.get(key) for m in maps))
return result
def test_connect():
from pprint import pprint, pformat
collA = [
{"id": 123, "name": "Hello"},
{"id": 456, "name": "Foo"},
]
collB = [
{"id": 456, "data": "def"},
{"id": 123, "data": "abc"},
]
result = connect(
(collA, lambda x: x["id"]),
(collB, lambda x: x["id"]))
assert result == [
({"id": 123, "name": "Hello"}, {"id": 123, "data": "abc"}),
({"id": 456, "name": "Foo"}, {"id": 456, "data": "def"}),
], pformat(result)
groups = [
{"groupId": 2, "name": "group 2"},
{"groupId": 1, "name": "group 1"},
{"groupId": 3, "name": "group 3"},
]
ads = [
{"groupId": 2, "ad": "some ad"},
]
banners = [
{"groupId": 3, "banner": "some banner"},
]
result = connect(
(groups, lambda g: g["groupId"]),
(ads, lambda a: a["groupId"]),
(banners, lambda b: b["groupId"]))
assert result == [
({"groupId": 2, "name": "group 2"}, {"groupId": 2, "ad": "some ad"}, None),
({"groupId": 1, "name": "group 1"}, None, None),
({"groupId": 3, "name": "group 3"}, None, {"groupId": 3, "banner": "some banner"}),
], pformat(result)
if __name__ == "__main__":
test_connect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment