Answer the question
In order to leave comments, you need to log in
How can you merge two or more dictionaries?
This is:
collections = [{'href': 'link1', 'wait': 1},
{'href': 'link1', 'wait': 2},
{'href': 'link2', 'wait': 1},
{'href': 'link3', 'wait': 0}]
collections = [{'href': 'link1', 'wait': 3},
{'href': 'link2', 'wait': 1},
{'href': 'link3', 'wait': 0}]
Answer the question
In order to leave comments, you need to log in
For real dictionary merging
, you need not to merge dictionaries
result = []
for c in collections:
inced = 0
for n, collection in enumerate(result):
if collection["href"] == c["href"]:
result[n]["wait"] += c["wait"]
inced = 1
if inced == 0: result.append(c)
result = []
for c in collections:
for n, collection in enumerate(result):
if collection["href"] == c["href"]:
result[n]["wait"] += c["wait"]
break
else: result.append(c)
def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
z = merge_dicts(a, b, c, d, e, f, g)
res = defaultdict(int)
for d in collections:
res[d['href']] += d['wait']
res = [dict(zip(('href', 'wait'), c)) for c in sorted(res.items())]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question