Created
December 15, 2011 18:12
-
-
Save mattdeboard/1482144 to your computer and use it in GitHub Desktop.
Function that will sum the values of two dictionaries with at least one key shared between them.
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 add_dicts(svs): | |
""" | |
Performs an "add" operation on multiple SavedSearch attribute dictionaries | |
to create a single attribute dictionary object by which we can perform | |
filtering operations between multiple SavedSearch results. | |
""" | |
if not svs: | |
return {} | |
# Only iterate over the keys that exist in both dictionaries | |
attr_dicts = (i._attr_dict() for i in svs) | |
keys = reduce(operator.or_, (set(i) for i in attr_dicts)) | |
results = [] | |
for k in keys: | |
# The values of the attr dicts on SavedSearch objects are lists, | |
# so we use the __add__ method on lists to combine all the values | |
# for a given key across multiple dictionaries with this reduce | |
# call. | |
vals = reduce(operator.add, (i.get(k, []) for i in attr_dicts)) | |
# Before appending the results to the `results` list, filter out | |
# any items in the value list that evaluate to False (e.g. empty | |
# strings) | |
results.append((k, filter(lambda x: x, vals))) | |
# Coerce the `results` list to a dict and return. | |
return dict(results) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment