Y
Y
Yoshinon Eared2018-03-14 03:49:51
Python
Yoshinon Eared, 2018-03-14 03:49:51

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}]

In it:
collections = [{'href': 'link1', 'wait': 3},
               {'href': 'link2', 'wait': 1},
               {'href': 'link3', 'wait': 0}]

I tried using Counter, but it only works if the key values ​​are numbers. Well, or I did something wrong there :)
Thank you in advance for your help! The decision does not come to mind, well, not at all.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Max Payne, 2018-03-14
@Aquinary

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)

You can try like this
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)

K
kzoper, 2018-03-14
@kzoper

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)

A
Animkim, 2018-03-14
@Animkim

res = defaultdict(int)
for d in collections:
    res[d['href']] += d['wait']
res = [dict(zip(('href', 'wait'), c)) for c in sorted(res.items())]

Python2, on the third one, maybe something needs to be fixed. Most of the code is engaged in restoring the original structure, I think you can write it easier. I proceeded from the fact that we know in advance the keys of the dictionary and their number.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question