Last active
May 18, 2016 08:54
-
-
Save bofm/d7ff842d90dff6547ddd25a4b03a2806 to your computer and use it in GitHub Desktop.
Python merge records (lists of dicts) by key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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