Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bofm
Last active May 18, 2016 08:54
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 bofm/d7ff842d90dff6547ddd25a4b03a2806 to your computer and use it in GitHub Desktop.
Save bofm/d7ff842d90dff6547ddd25a4b03a2806 to your computer and use it in GitHub Desktop.
Python merge records (lists of dicts) by key
def merge_records_by_key(dicts1, dicts2, key):
"""Updates each dict1 containing key `key` from `dicts1`
with the corresponding dict2 from `dicts2` having
dict1[key] == dict2[key].
"""
if len(dicts1) > len(dicts2):
probe, build = dicts1, dicts2
hashmap = {d[key]: d for d in build if key in d}
def up(d):
d.update(hashmap[d[key]])
else:
probe, build = dicts2, dicts1
hashmap = {}
for d in build:
if key in d:
hashmap.setdefault(d[key], []).append(d)
def up(d):
for x in hashmap[d[key]]:
x.update(d)
for d in probe:
with suppress(KeyError):
up(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment