def dict_combine(dict1, dict2, combiner):
"""takes two dictionaries and combines them
such that the value is the result of:
result[a] = combiner(dict1[a],dict2[a])"""
result = {}
dict1_keys = set(dict1.keys())
dict2_keys = set(dict2.keys())
# keys uniuqe to dict1 are included unchanged
for x in dict1_keys - dict2_keys:
result[x] = dict1[x]
# keys uniuqe to dict2 are included unchanged
for x in dict2_keys - dict1_keys:
result[x] = dict2[x]
# keys in both dictionaries get combined then included
for x in dict1_keys & dict2_keys:
result[x] = combiner(dict1[x],dict2[x])
return result
def test_dict_combine():
dict1 = dict(a=1, b=2, c=3)
def adder(a,b):
return a + b
assert dict_combine(dict1,dict1,adder) == dict(a=2, b=4, c=6)
test_dict_combine()
Combining Python Dictionaries
Friday, 5 June 2009
I had a small task where I had to take two existing dict and combine them by adding together the values of any elements that already exist. Here's how I did it.
Labels:
programming,
python
Subscribe to:
Post Comments (Atom)
0 comments
Post a Comment